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前面.                    
0 0