作者tonytonyjan (南洋大兜蟲)
看板Ruby
標題[問題] Is "ensure" useless?
時間Fri Mar 30 15:24:52 2012
感覺 ensure 沒有什麼用
最常舉的例子就是處理 IO:
begin
file = open("/tmp/some_file", "w")
# Write to the file.
rescue
# Handle the exceptions.
ensure
file.close # this always happens.
end
但是這樣也行吧:
begin
file = open("/tmp/some_file", "w")
# Write to the file.
rescue
# Handle the exceptions.
end
file.close # this always happens too.
有沒有 ensure 沒有什麼用的八卦?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.246.1
推 mars90226:不是喔,如果前面要return,還是會執行ensure 03/30 16:37
推 yzugsr:另外,ensure也可以不rescue 03/30 19:37
→ tonytonyjan:to mars: 剛實驗了一下,你沒說我還沒發現! 敬受教! 03/30 19:41
→ godfat:ensure 又不是只用在 file handle 上... XD 03/30 20:31
→ godfat:另外其實還有 else clause... 是 rescue 的 dual 03/30 20:33