LoginSignup
1
1

More than 5 years have passed since last update.

begin rescueのエラー処理でrescue中で発生したエラーをrescueできるか検証

Last updated at Posted at 2019-03-11

前提条件

検証バージョン: Ruby2.6.1

結論

できる

検証用のメソッド
raiseでエラーを発生させ、rescueでエラーキャッチしたその中でまたエラーを発生してrescueでキャッチしている

def method
  p 'init'
  begin
    raise "first error"
  rescue
    p "first rescue"
    begin
      raise 'second error'
    rescue
      p 'second rescue'
    end
  end
end

実行結果

> method
"init"
"first rescue"
"second rescue"

このようにbeginを書かないでブロックを1段階外にrescueを書く方法もある

def method2
  p 'init'
  raise "first error"
rescue
  p "first rescue"
  begin
    raise 'second error'
  rescue
    p 'second rescue'
  end
end

実行結果

> method2
"init"
"first rescue"
"second rescue"
1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1