8-2-2 各種メソッドで例外処理を記述しよう
トップレベルで定義したメソッドで例外処理するプログラムを記述し保存する
以下のようにプログラムを記述し、ファイル名をexception_in_method1.rb
で保存します。
def exception_in_method begin a rescue => e p e.message ensure p 'begin block is end.' end end exception_in_method
トップレベルで定義したメソッドで例外処理するプログラムを実行する
コマンドライン上で保存したプログラムを指定して実行します。実行結果に"undefined local variable or method `a' for main:Object"
と"begin block is end."
が表示されます。
$ ruby exception_in_method1.rb "undefined local variable or method `a' for main:Object" "begin block is end."
begin
句を省略するプログラムを記述し保存する
以下のようにプログラムを記述し、ファイル名をexception_in_method2.rb
で保存します。
def exception_in_method a rescue => e p e.message ensure p 'begin block is end.' end exception_in_method
begin
句を省略するプログラムを実行する
コマンドライン上で保存したプログラムを指定して実行します。実行結果に"undefined local variable or method `a' for main:Object"
と"begin block is end."
が表示されます。
$ ruby exception_in_method2.rb "undefined local variable or method `a' for main:Object" "begin block is end."
クラスのメソッドに例外処理するプログラムを記述し保存する
以下のようにプログラムを記述し、ファイル名をexception_in_method3.rb
で保存します。
class ExceptionCatcher def catch a rescue => e p e.message ensure p 'begin block is end.' end end catcher = ExceptionCatcher.new catcher.catch
クラスのメソッドに例外処理するプログラムを実行する
コマンドライン上で保存したプログラムを指定して実行します。実行結果に"undefined local variable or method `a' for main:Object"
と"begin block is end."
が表示されます。
$ ruby exception_in_method3.rb "undefined local variable or method `a' for main:Object" "begin block is end."