LoginSignup
0
0

More than 3 years have passed since last update.

Rubyの例外処理まとめ

Last updated at Posted at 2020-03-19

そもそも例外とは?

プログラム実行中に発生したエラーの意。
例外処理を記述しないと、例外発生時点でプログラムが停止してしまい、それ以降に記述してあるコードが読み込まれない。
Rubyで例外を補足するためにはrescueメソッドを用いる。

例外の種類

Ruby公式リファレンスを参照。

begin~rescue

例)「1/0」の箇所で、整数は0では割れないため、「ZeroDivisionError」という例外が発生。

begin
  1/0
rescue => e
  puts e
end

#=> divided by 0

eには例外オブジェクト(ZeroDivisionErrorなど)が代入されるので、それら例外オブジェクトに実装されている基本的なメソッドを使用することができる。
- class : 例外の種類
- message : 例外のメッセージ
- backtrace : 例外発生の位置情報

begin
  1/0
rescue StandardError => e
  puts e
  puts e.class
  puts e.class.superclass
  puts e.message
end

#=> divided by 0
#=> ZeroDivisionError
#=> StandardError
#=> divided by 0

応用メソッド(ensure/retry/raise/File.open)

ensure:例外の有無に関わらず実行される

begin
  1/0
rescue => e
  puts e
ensure
  puts "ensure"
end

#=> ensure

retry:beginからの実行をもう一度やり直す

count = 0
begin
  1/0
rescue
  p count += 1
  retry if count < 3
  puts "failed"
end 

#=> 1
#=> 2
#=> 3
#=> failed

raise:意図的に例外を起こす

begin
  raise
  rescue
    p "例外です"
end

#=> 例外です
0
0
1

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