前提条件
- Ruby 3.1.0
- Rails 7.0.4
やりたいこと
作成した機能に例外処理を追加したい。
方法
begin - rescueを使う
begin
# 普通の処理
rescue => e
# 例外時の処理
end
補足
- beginを省略することができる。
def foo
# 普通の処理
rescue => e
# 例外時の処理
end
- 例外クラスを指定することができる。
def foo
# 普通の処理
rescue <例外クラス名> => e
# 例外時の処理
end
※例外クラスは下記参照
https://docs.ruby-lang.org/ja/2.1.0/library/_builtin.html
参考