2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RubyのStandardErrorとそのサブクラスの理解

Posted at

RubyのStandardErrorとそのサブクラスの理解

Rubyにおける例外処理は、Exceptionクラスを基底とする階層構造で成り立っています。その中でも、StandardErrorは最も一般的な例外クラスであり、rescue節で特定の例外クラスを指定しない場合、デフォルトでStandardErrorおよびそのサブクラスが捕捉されます。

StandardErrorの主なサブクラス一覧

以下は、StandardErrorの主なサブクラスです:

  • ArgumentError
  • EncodingError
  • FiberError
  • IOError
    • EOFError
  • IndexError
    • KeyError
    • StopIteration
  • LocalJumpError
  • NameError
    • NoMethodError
  • RangeError
    • FloatDomainError
  • RegexpError
  • RuntimeError
  • SystemCallError
    • Errno::*(システム依存のエラー)
  • ThreadError
  • TypeError
  • ZeroDivisionError

これらのエラーは、rescue節で例外クラスを指定しない場合に捕捉されます。一方、Exceptionクラスの他のサブクラス(例:NoMemoryErrorScriptErrorSystemExitなど)は、明示的に指定しない限り捕捉されません。

StandardErrorを継承しているかの確認方法

Rubyのコンソール(IRBやRailsコンソール)で、特定の例外クラスがStandardErrorを継承しているかを確認するには、<演算子やancestorsメソッドを使用します。

# `<`演算子を使用して確認
ZeroDivisionError < StandardError
# => true

# `ancestors`メソッドを使用して確認
ZeroDivisionError.ancestors.include?(StandardError)
# => true

また、StandardErrorのすべてのサブクラスを一覧表示するには、以下のようにします:

# Ruby 2.0以降で使用可能
ObjectSpace.each_object(Class).select { |klass| klass < StandardError }

このコードは、StandardErrorを継承しているすべてのクラスを配列として返します。ただし、すべてのクラスが読み込まれているとは限らないため、結果は実行環境によって異なる場合があります。
自分の環境だと使っているgemの例外クラスなどが出てきました。

これらの方法を使用することで、特定の例外クラスがStandardErrorを継承しているかどうかを確認できます。

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?