ruby 異常處理:ensure
更新時間:2007年11月24日 14:22:03 作者:
當一個方法結(jié)束工作時我們也許需要進行清理工作.也許一個打開的文件需要關(guān)閉,緩沖區(qū)的數(shù)據(jù)應清空等等.如果對于每一個方法這里永遠只有一個退出點,我們可以心安理得地將我們的清理代碼放在一個地方并知道它會被執(zhí)行;但一個方法可能從多個地方返回,或者因為異常我們的清理代碼被意外跳過.
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
end
上面,如果在我們寫文件的時候發(fā)生異常,文件會保留打開.我們也不希望這樣的冗余出現(xiàn):
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"體系中加入了一個關(guān)鍵字 ensure. 無論begin塊是否成功,ensure代碼域都將執(zhí)行.
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
上面,如果在我們寫文件的時候發(fā)生異常,文件會保留打開.我們也不希望這樣的冗余出現(xiàn):
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"體系中加入了一個關(guān)鍵字 ensure. 無論begin塊是否成功,ensure代碼域都將執(zhí)行.
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前面.
相關(guān)文章
關(guān)于Ruby on Rails視圖編寫的一些建議
這篇文章主要介紹了關(guān)于Ruby on Rails視圖編寫的一些建議,有助于團隊協(xié)作時對代碼的調(diào)試工作,需要的朋友可以參考下2015-08-08ruby 小腳本搞定CVS服務器更換后checkout下來的工程遷移
CVS換了新的服務器,原來的工程需要更改Server配置,這個東東手工做起來 可是個體力活,寫了一個腳本分發(fā)下來。2008-12-12