Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Kernel | raise

概要

Kernel#raise -> ()
Kernel#raise(message) -> ()
Kernel#raise(error_type, message = nil, backtrace = caller(0)) -> ()

詳細

例外を発生させる。
発生した例外は変数 $! に格納される。
また例外が 発生した時のスタックトレースは変数 $@ に格納される。
発生した例外は rescue 節で捕捉できる。

・引数無しの場合
同スレッドの同じブロック内で最後に rescue された 例外オブジェクト ($!) を再発生させます。
そのような 例外が存在しないが自身は捕捉されている時には例外 RuntimeError を発生させます。

・message 引数ありの場合
RuntimeErrorに例外メッセージを設定して、例外を発生させる。

error_type, message 引数ありの場合
error_typeで指定したエラーに例外メッセージを設定して、例外を発生させる。

Kernel#raise と Kernel#fail の使い分け

文法的な違いはないが、Ruby Style Guideでは
・例外を発生させる場合は fail を利用する
・例外をキャッチして、再発生させる場合は raise を利用すること
が推奨される。

下記のExceptionの説明を参照
https://github.com/fortissimo1997/ruby-style-guide/blob/japanese/README.ja.md
https://github.com/bbatsov/ruby-style-guide

サンプルコード
require 'test_toolbox'

def hoge_argument_error
  raise ArgumentError, 'invalid argument'
rescue
  puts "catch #{$!}"
  raise
end

def hoge_runtime_error
  raise 'runtime error'
rescue
  puts "catch #{$!}"
  raise
end

begin
  hoge_argument_error
rescue
  puts $!.class
  puts $!
end

dp_line __LINE__

begin
  hoge_runtime_error
rescue
  puts $!.class
  puts $!
end

__END__
dp_lineはtbpgr_utils gemの機能です。
printデバッグ時の目印が目的のメソッドです。

詳しくは下記参照。
https://github.com/tbpgr/tbpgr_utils

出力

catch invalid argument
ArgumentError
invalid argument
--------------------|filename=|line=24|--------------------
catch runtime error
RuntimeError
runtime error