ruby 異常處理:ensure
来源:互联网 发布:excel数据怎么汇总 编辑:程序博客网 时间:2024/05/16 07:22
當一個方法結束工作時我們也許需要進行清理工作.也許一個打開的文件需要關閉,緩衝區的數據應清空等等.如果對於每一個方法這裡永遠只有一個退出點,我們可以心安理得地將我們的清理代碼放在一個地方並知道它會被執行;但一個方法可能從多個地方返回,或者因為異常我們的清理代碼被意外跳過.
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
end
上面,如果在我們寫文件的時候發生異常,文件會保留打開.我們也不希望這樣的冗餘出現:
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
rescue
file.close
fail # raise an exception
end
這是個笨辦法,當程序增大時,代碼將失去控制,因為我們必須處理每一個 return 和 break,.
為此,我們向"begin...rescue...end"體系中加入了一個關鍵字 ensure. 無論begin塊是否成功,ensure代碼域都將執行.
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
rescue
# ... handle the exceptions ...
ensure
file.close # ... and this always happens.
end
可以只用ensure或只用rescue,但當它們在同一begin...end域中時, rescue 必須放在 ensure前面.
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
end
上面,如果在我們寫文件的時候發生異常,文件會保留打開.我們也不希望這樣的冗餘出現:
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
rescue
file.close
fail # raise an exception
end
這是個笨辦法,當程序增大時,代碼將失去控制,因為我們必須處理每一個 return 和 break,.
為此,我們向"begin...rescue...end"體系中加入了一個關鍵字 ensure. 無論begin塊是否成功,ensure代碼域都將執行.
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
rescue
# ... handle the exceptions ...
ensure
file.close # ... and this always happens.
end
可以只用ensure或只用rescue,但當它們在同一begin...end域中時, rescue 必須放在 ensure前面.
0 0
- ruby 異常處理:ensure
- ruby 异常处理:ensure
- ruby 异常处理:ensure
- Ruby中用begin/end …rescue…ensure … raise 来处理异常
- ruby
- ruby
- ruby
- Ruby
- Ruby
- Ruby
- ruby
- ruby
- ruby
- Ruby
- RUBY
- ruby
- Ruby
- ruby
- 跳台阶
- Ruby教程之注釋、變數聲明以及數組操作
- ruby 存取器 概念
- 2015 SDK更新慢,SDK更新不了方法
- 含vtk64位库的程序运行0xc000007b错误的解决
- ruby 異常處理:ensure
- 初步了解一下什麼是ruby
- Link in the HTML--Head first into HTML
- 指针学习九
- 背包问题
- mysql学习笔记之十五(日志管理)
- 面试题44:扑克牌的顺子
- Ruby 中一些百分號(%)的用法小結
- rails上傳圖片代碼實例