LoginSignup
27
23

More than 5 years have passed since last update.

rescue Exception を安易に使うべきではない理由

Last updated at Posted at 2012-11-16

RubyにおいてExceptionクラスは各種例外クラスの親クラスになっているが、その派生クラスにはInterruptも含まれる。

そのため、rescue Exception とした場合、ctrl+c でプログラムを停止しようとした場合にそのシグナルも捕捉されてしまい、プログラムが停止できなくなる。(そのような場合、kill -9コマンドなどでプロセスを強制停止することになる)

危険なコード

bad_rescue.rb
begin
  # なんらかの処理
rescue Exception
  # 割り込みを含むすべての例外をキャッチしてしまう
end

改善したコード

better_code.rb
begin
  # 何らかの処理
rescue
  # StandardError およびそのサブクラスのみキャッチ
end

または

better_code.rb
begin
  # 何らかの処理
rescue SomeException => e
  # SomeException およびそのサブクラスのみキャッチ
end

参考

Why is it bad style to 'rescue Exception => e' in Ruby?

27
23
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
27
23