142
122

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Ruby] 例外処理を実装する時のrescue書き方3パターン

Posted at

1. 普通にbegin~rescue

begin
  # 普通の処理
rescue => e
  # 例外時の処理
end

eに例外オブジェクトが入ってきます。

2. メソッド単位でrescue

def foo
  # 普通の処理
rescue => e
  # 例外時の処理
end

begin省略してちょっとすっきりします。

3. 1行でrescue

some_method rescue p $!

1行で書く場合は$!で例外オブジェクトを取得できますね。

その他

その他の例外関連はこちらなどを参考に
http://www.namaraii.com/rubytips/?%E4%BE%8B%E5%A4%96

142
122
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
142
122

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?