脳汁portal

アメリカ在住(だった)新米エンジニアがその日学んだIT知識を書き綴るブログ

Rubyの例外処理について

Rubyの例外の種類

f:id:portaltan:20150907174556p:plain

例外処理の基本的な書き方

記法
begin
  ${例外処理した処理}
rescue => ${例外の内容を格納する変数}
  ${例外が発生したときに行う処理}
ensure
  ${例外発生の有無に関わらずに、最後に実行する処理}
end
Example
def test_exception
  raise ZeroDivisionError.new("Oops!!! test_exception return the exception!!")
end

begin
  test_exception
rescue => e
  puts "#{e.class}"
  puts "#{e.message}"
ensure
  puts "script has finished"
end

自作例外の作成(宣言)方法

記法
class ${自作例外クラス} < ${元になる例外クラス}; end
Example
module SelfException 
  class TestError1 < StandardError; end
  class TestError2 < TestError1; end
end

include SelfException

begin
  raise TestError1
rescue TestError2
  puts "rescue area of TestError2"
rescue TestError1
  puts "rescue area of TestError1"
rescue StandardError
  puts "rescue area of StandardError"
end
  • rescueでは引数に例外クラスを与えることでキャッチする例外を限定できます。
  • 例外クラスを継承することによって自分で好きな名前の例外を設定することが出来ます。

継承した場合

継承元の例外はキャッチしません

begin
  raise   # 何も引数ないとStandardError
rescue TestError1
  puts "rescue area of TestError1"
rescue StandardError
  puts "rescue area of StandardError"  # <== これが呼ばれる
end
  • raiseに引数を与えないとデフォルトでStandardErrorになります。

継承先のエラーは継承元の例外クラスでrescueできます

begin
  raise  TestError1
rescue StandardError
  puts "rescue area of StandardError"  # <== これが呼ばれる
rescue TestError1
  puts "rescue area of TestError1"
end