LoginSignup
3
0

【Ruby Gold3.1詰まったシリーズ】raiseメソッドの動き

Last updated at Posted at 2023-12-07

はじめに

今回はraiseに関する内容です。raiseは呼び出す場所によって働きが異なるらしいので簡単にまとめてみます。

確認してみた

環境はruby2.5.3です。
まず、例外を発生させ、rescueの中にraiseを記載した

begin
  "adventcalendar".hoge
rescue NameError
  raise
end

を実行すると、

Traceback (most recent call last):
        2: from /usr/local/bin/irb:11:in `<main>'
        1: from (irb):2
NoMethodError (undefined method `hoge' for "adventcalendar":String)

が表示され、beginで発生した例外NoMethodError をraiseで再度呼び出している。
次に、beginの中にもraiseを記載した

begin
  raise
rescue 
  raise
end

を実行すると、

Traceback (most recent call last):
        2: from /usr/local/bin/irb:11:in `<main>'
        1: from (irb):2
RuntimeError ()

が表示され、rescueの中のraiseで再度呼び出した例外がRuntimeErrorなので、beginの中のraiseはRuntimeErrorを発生させている。

おわりに

確認した結果、beginの中でraiseを呼び出すとRuntimeErrorを発生させ、rescueの中でraiseを呼び出すとbeginで発生した例外を再度呼び出せることが分かった。もし誤っていたらご指摘いただけると助かります!

参考

3
0
0

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
3
0