例外処理・ensureで後処理
スポンサーリンク
スポンサーリンク
ライフスタイル関連のコンテンツ
お金 | 仕事 | 勉強 | プライベート | 健康 | 心
プログラミング関連のコンテンツ
C言語/C++入門 | Ruby入門 | Python入門 | プログラミング全般
お金 | 仕事 | 勉強 | プライベート | 健康 | 心
プログラミング関連のコンテンツ
C言語/C++入門 | Ruby入門 | Python入門 | プログラミング全般
ensure節を、begin~rescueの後に続けることで、例外発生の有無に関わらず、実行させる処理を書くことができます。
例外処理のスクリプト例で書いたコードに、ensure節の後処理を加えてみます。
スポンサーリンク
begin
filenames = ['hello.dat', 'no_such_file.dat']
filenames.each { |filname|
file = open(filname)
puts file.read
file.close
}
rescue => ex
puts ex.class # 例外の種類
puts ex.message # 例外メッセージ
puts ex.backtrace # 例外発生の位置情報
ensure
if ex
puts "Exception Error"
else
puts "No Exception Error"
end
end
実行結果。
Hello, Yamada ! Today is beautiful day ! Errno::ENOENT No such file or directory - no_such_file.dat ex_test.rb:4:in `initialize' ex_test.rb:4:in `open' ex_test.rb:4 ex_test.rb:3:in `each' ex_test.rb:3 Exception Error
では、以下のようにno_such_file.datをオープンしないで、例外が発生しない場合。
begin
filenames = ['hello.dat', 'hello.dat']
filenames.each { |filname|
file = open(filname)
puts file.read
file.close
}
rescue => ex
puts ex.class # 例外の種類
puts ex.message # 例外メッセージ
puts ex.backtrace # 例外発生の位置情報
ensure
if ex
puts "Exception Error"
else
puts "No Exception Error"
end
end
実行結果。
Hello, Yamada ! Today is beautiful day ! Hello, Yamada ! Today is beautiful day ! No Exception Error
例外が発生しようと、発生しなかろうと、ensure節の処理が行われています。
スポンサーリンク
<< 前の記事 : 例外処理のスクリプト例
- - 関連記事 -
- 例外処理のスクリプト例
- 例外処理・エラーを捕まえる
スポンサーリンク