1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have 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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?