例外処理のサンプル。
#オリジナルで例外を作る
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)
後処理です