4月 7th, 2008at 16:23

Tags:

Ruby1.8.5で例外処理を試す

例外処理のサンプル。

#オリジナルで例外を作るclass SystemException < Exception

  #trace、messageからメッセージを作成します。  def getAllMessage()    return "#{backtrace}: #{message} (#{self.class})"  end

end

password = "****X"

#トップレベルで例外処理begin

  if password == "*****" then    puts "認証OK"  else    raise SystemException.new("認証に失敗しました。")  end

rescue SystemException => e  #狙ってキャッチする例外  puts e.getAllMessage()  #投げなおす場合は↓  #raise

rescue => e  #予期せぬ例外をキャッチする場合  puts "SystemException以外の例外です。"

else  #begin節の最後までいったら実行される  puts "begin節は正常に終了しました。"

ensure  puts "後処理です"end

実行結果

D:/daipresents/project/ruby/src/test/exception_test.rb:22: 認証に失敗しました。 (SystemException)後処理です