Ruby 資料一覧
制御
2007/8/21更新
対応バージョン: 1.8
例外処理の記述方法
以下の節を組み合わせて使用する。
begin : 主処理
rescure : 例外処理(オプション)
ensure : 終了前処理(オプション)
例)
file = "./non_exist"
begin # 主処理
f = open(file)
puts "opened => #{file}"
rescue # begin節内の例外発生時に実行される
puts $! # 例外メッセージを出力
file = "/etc/host.conf" # 実在するファイルを指定
retry # begin節を再実行
ensure # begin節を抜ける直前に実行される
f.close
end
上記の例ではあるファイルをオープンしようとして例外(file not found)が発生し、再度rescue節にて指定した実在するファイルをオープンしている。
これを実行すると以下のような結果になる。
No such file or directory - ./non_exist opened => /etc/host.conf