當一個方法結(jié)束工作時我們也許需要進行清理工作.也許一個打開的文件需要關(guān)閉,緩沖區(qū)的數(shù)據(jù)應清空等等.如果對于每一個方法這里永遠只有一個退出點,我們可以心安理得地將我們的清理代碼放在一個地方并知道它會被執(zhí)行;但一個方法可能從多個地方返回,或者因為異常我們的清理代碼被意外跳過.
begin
file=open("/tmp/some_file","w")
#...writetothefile...
file.close
end
上面,如果在我們寫文件的時候發(fā)生異常,文件會保留打開.我們也不希望這樣的冗余出現(xiàn):
begin
file=open("/tmp/some_file","w")
#...writetothefile...
file.close
rescue
file.close
fail#raiseanexception
end
這是個笨辦法,當程序增大時,代碼將失去控制,因為我們必須處理每一個return和break,.
為此,我們向"begin...rescue...end"體系中加入了一個關(guān)鍵字ensure.無論begin塊是否成功,ensure代碼域都將執(zhí)行.
begin
file=open("/tmp/some_file","w")
#...writetothefile...
rescue
#...handletheexceptions...
ensure
file.close#...andthisalwayshappens.
end
可以只用ensure或只用rescue,但當它們在同一begin...end域中時,rescue必須放在ensure前面.