LoginSignup
53
48

More than 3 years have passed since last update.

【Ruby】例外処理まとめ

Last updated at Posted at 2019-07-31

概要

Rubyの例外処理に関して最低限必要な知識を簡単なコードと共にまとめました。

基本文法

例外処理の基本は以下の様な形式になります。

begin 
  # エラーを発生させる可能性のあるコード。
rescue => e # 例外オブジェクトを代入した変数。
  # begin~rescueの間でエラーが発生した場合に実行されるコード。
end

コード例

begin 
  raise # エラーを発生させます。
rescue => e
  p e #=> RuntimeError
end

関連メソッド

Method Explanation
Object#class エラーのクラスを返します。
Kernel#raise エラーを発生させます。
Exception#backtrace エラーのバックトレースを返します。
Exception#message エラーのメッセージを返します。

コード例

begin 
  raise StandardError.new("Message")
rescue => e
  p e.class #=> StandardError
  p e.message #=> "Message"
  p e.backtrace #=> ["(repl):4:in `<main>'", "/run_dir/repl.rb:41:in `eval'", "/run_dir/repl.rb:41:in `run'", "/run_dir/repl.rb:57:in `handle_eval'", "/run_dir/repl.rb:170:in `start'", "/run_dir/repl.rb:177:in `start'", "/run_dir/repl.rb:181:in `<main>'"]
end

Ensure

ensureを使用する事でエラーの有無に関わらず処理を実行する事ができます。

コード例1(エラーがない場合)

begin 
  "no Error"
rescue => e
  p e.message # エラーはないので実行されません。
ensure 
  p "絶対実行" #=> 絶対実行
end

コード例2(エラーが発生した場合)

begin 
  raise StandardError.new('error')
rescue => e
  p e.message #=> error
ensure 
  p "絶対実行" #=> 絶対実行
end

Retry

文字通り処理を再実行します。

コード例

file = ARGV[0]

begin
  io = File.open( file )
rescue
  # ファイルを開く際にエラーが発生した場合は処理が行われる。
  sleep( 10 )
  # begin ~ rescue内の処理を再び実行します。
  retry
end

Rescue修飾子

if修飾子のように rescueを修飾子として使用する事ができます。

コード例

raise "Error" rescue p "rescued" #=> rescued

メソッド内の例外

メソッド内ではbeginendを省略して以下のように書く事ができます。

def method
  # エラーを発生させる可能性のあるコード。
 rescue => e 
  # エラー発生時の処理。
end

コード例

def method
 raise 'error'
 rescue => e 
  p e.message #=> error
 ensure
  p 'ensured' #=> ensured
end
method #=> "error"

複数の例外処理

以下のように対応するエラー毎に複数のrescueを記載する事で、各エラー毎に別の対応をする事ができます。

begin 
  rescue Exception1, Exception2 => e
  # Exception1 か Exception2が発生した際に処理が実行される。
  rescue Exception3 => e
  # Exception3が発生した際に処理が実行される。
  rescue => e
   # Exception1,2,3以外の例外が発生した際に処理が実行される。
end

コード例

begin 
  raise StandardError
  rescue StandardError, RangeError   
    p 'Standard or Range Error'
  rescue RuntimeError
    p 'Runtime Error'
  rescue => e
    p 'some other error'
end

#=> "Standard or Range Error"

カスタム例外の作成

以下の記事にカスタム例外の作成方法をまとめました。
【Ruby】カスタム例外を作成する簡単3ステップ - Qiita

参照

Ruby Exception handling - DEV Community 👩‍💻👨‍💻

53
48
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
53
48