Skip to content

Instantly share code, notes, and snippets.

@sunaot
Created March 10, 2014 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunaot/9463401 to your computer and use it in GitHub Desktop.
Save sunaot/9463401 to your computer and use it in GitHub Desktop.
Ruby で Exception

Ruby でアプリケーション例外をつくるときの作り方。

begin
  # 通常の処理
rescue SomeErrorException => e
  # Exception から継承したクラスや StandardError から継承したクラスを指定で受ける
rescue => e # StandardError
  # 継承木に StandardError がいるクラスのみひっかかる
else
  # 例外が起きなかったときの処理
end

基本的には、

  • StandardError は例外クラス指定なしの rescue で受けられる。
  • Exception から継承すると、例外クラス指定なしの rescue で受けられないので個別指定で受ける。受け漏れると、Exception と同様に実行時エラーで失敗する。
  • 例外指定なしの raise では RuntimeError が発生する。RuntimeErrorStandardError のサブクラス。

ことから、StandardError を継承して定義するのがよい。Exception を継承し、StandardError を継承しないのは、NoMemoryErrorSyntaxError などのように握りつぶすと致命的になるような例外なので、アプリケーションエラーでは使用しない (するなら、同等の致命的な復旧不可能のエラーの場合のみとする) 。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment