作者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
1F:推 mars90226:不是喔,如果前面要return,还是会执行ensure 03/30 16:37
2F:推 yzugsr:另外,ensure也可以不rescue 03/30 19:37
3F:→ tonytonyjan:to mars: 刚实验了一下,你没说我还没发现! 敬受教! 03/30 19:41
4F:→ godfat:ensure 又不是只用在 file handle 上... XD 03/30 20:31
5F:→ godfat:另外其实还有 else clause... 是 rescue 的 dual 03/30 20:33