LoginSignup
28
33

More than 5 years have passed since last update.

rescue節で例外の型を指定しない場合に補足できるのはStandardErrorとそのサブクラスだけ

Last updated at Posted at 2012-09-09

Javaや.NETをやってた人にしてみると、Exceptionクラスは普通の例外の代表のように考えてしまうかもしれません。
しかしRubyのExceptionNoMemoryError等の致命的な例外の親クラスにもなっているため、例外の型を指定しないrescue節では補足されません。
補足されるのは通常の実行時エラーを表すStandardErrorとそのサブクラス(ArgumentError等)になります。

require 'rspec'

describe 'rescue' do
  shared_examples_for 'rescue StandardError' do
    it 'should rescue StandardError' do
      -> { subject.call(StandardError) }.should_not raise_error
    end
  end

  context 'when not specify exception' do
    subject do
      ->(e) {
        begin
          raise e
        rescue
        end
      }
    end

    it 'should not rescue Exception' do
      -> { subject.call(Exception) }.should raise_error(Exception)
    end

    it_should_behave_like 'rescue StandardError'
  end

  context 'when specify exception' do
    subject do
      ->(e) {
        begin
          raise e
        rescue Exception
        end
      }
    end

    it 'should rescue Exception' do
      -> { subject.call(Exception) }.should_not raise_error
    end

    it_should_behave_like 'rescue StandardError'
  end
end
$ rspec rescue_spec.rb
....

Finished in 0.00162 seconds
4 examples, 0 failures

Rubyの例外の階層関係についてはこちらのページの図がわかりやすいです。

例外クラスを自分で定義する場合も通常はExceptionクラスではなく、StandardErrorクラスのサブクラスにすべき、ということになりますね。

参考ページ

28
33
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
28
33