當(dāng)一個(gè)方法結(jié)束工作時(shí)我們也許需要進(jìn)行清理工作.也許一個(gè)打開(kāi)的文件需要關(guān)閉,緩沖區(qū)的數(shù)據(jù)應(yīng)清空等等.如果對(duì)于每一個(gè)方法這里永遠(yuǎn)只有一個(gè)退出點(diǎn),我們可以心安理得地將我們的清理代碼放在一個(gè)地方并知道它會(huì)被執(zhí)行;但一個(gè)方法可能從多個(gè)地方返回,或者因?yàn)楫惓N覀兊那謇泶a被意外跳過(guò).
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
end
上面,如果在我們寫(xiě)文件的時(shí)候發(fā)生異常,文件會(huì)保留打開(kāi).我們也不希望這樣的冗余出現(xiàn):
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
rescue
file.close
fail # raise an exception
end
這是個(gè)笨辦法,當(dāng)程序增大時(shí),代碼將失去控制,因?yàn)槲覀儽仨毺幚砻恳粋€(gè) return 和 break,.
為此,我們向"begin...rescue...end"體系中加入了一個(gè)關(guān)鍵字 ensure. 無(wú)論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,但當(dāng)它們?cè)谕籦egin...end域中時(shí), rescue 必須放在 ensure前面.