概要
Prefer top-level rescue clause
前提
Confident Rubyではメソッド内の処理を次のように分類しています。
・Collecting Inputs(引数チェック、変換など)
・Performing Work(主処理)
・Delivering Output(戻り値に関わる処理)
・Handling Failure(例外処理)
当記事は上記のうち、Handling Failureに関する話です。
サンプルコード仕様
メッセージを出力するメソッドを作成します。
メッセージが「hoge」だった場合のみ例外が発生します。
サンプル1:例外処理を begin/rescue/end で行います
サンプル2:例外処理を トップレベルの rescueで行います
サンプルコードその1
def puts_message_unless_hoge(msg) begin fail 'invalid msg hoge' if msg == 'hoge' puts msg rescue => e puts "you must not use 'hoge'" end end puts_message_unless_hoge "hige" puts_message_unless_hoge "hoge"
出力
hige you must not use 'hoge'
サンプルコードその1
def puts_message_unless_hoge(msg) fail 'invalid msg hoge' if msg == 'hoge' puts msg rescue => e puts "you must not use 'hoge'" end puts_message_unless_hoge "hige" puts_message_unless_hoge "hoge"
出力
hige you must not use 'hoge'