1
0

More than 1 year has passed since last update.

[Ruby] ExceptionとStandardErrorの違いを確認する

Posted at

:gear: はじめに

PythonやJavaでは一括でエラーをキャッチする際に、Exceptionクラスでキャッチしてしまいます。
ところが、RubyではExceptionではなくStandardErrorでキャッチするのが通常のようです。

:gear: StandardError で捕捉されるエラー

サンプルコード

begin
    raise NoMethodError
rescue StandardError => e
    puts "#{e.class} is a StandardError"
rescue Exception => e
    puts "#{e.class} is a Exception"
end

実行結果

NoMethodError is a StandardError

さらに、キャッチするエラーを明示的に指定しない場合もStandardErrorが捕捉されます。

サンプルコード

begin
    raise NoMemoryError
rescue => e
    puts "#{e.class} is a StandardError"
rescue Exception => e
    puts "#{e.class} is a Exception"
end

実行結果

NoMethodError is a StandardError

:gear: Exceptionで捕捉されるエラー

サンプルコード

begin
    raise NoMemoryError
rescue StandardError => e
    puts "#{e.class} is a StandardError"
rescue Exception => e
    puts "#{e.class} is a Exception"
end

実行結果

NoMemoryError is a Exception

独自例外の作成時もStandardErrorを継承する

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