Ruby-异常处理:ensure:修订间差异
来自站长百科
无编辑摘要 |
无编辑摘要 |
||
第1行: | 第1行: | ||
<span style="text-align:center; border:1px solid #000; float:right; padding:6px;"><strong>导航:</strong> [[Ruby学习教程#Ruby学习教程|上一页]] | {{template:开发语言导航}}</span> | <span style="text-align:center; border:1px solid #000; float:right; padding:6px;"><strong>导航:</strong> [[Ruby学习教程#Ruby学习教程|上一页]] | {{template:开发语言导航}}</span> | ||
<div style="clear:both;"></div> | <div style="clear:both;"></div> | ||
当一个方法结束工作时我们也许需要进行清理工作.也许一个打开的文件需要关闭,缓冲区的数据应清空等等.如果对于每一个方法这里永远只有一个退出点,我们可以心安理得地将我们的清理代码放在一个地方并知道它会被执行;但一个方法可能从多个地方返回,或者因为异常我们的清理代码被意外跳过. <br> | |||
begin<br> | |||
file = open("/tmp/some_file", "w")<br> | |||
# ... write to the file ...<br> | |||
file.close<br> | |||
end <br> | |||
上面,如果在我们写文件的时候发生异常,文件会保留打开.我们也不希望这样的冗余出现:<br> | |||
begin<br> | |||
file = open("/tmp/some_file", "w")<br> | |||
# ... write to the file ...<br> | |||
file.close<br> | |||
rescue<br> | |||
file.close<br> | |||
fail # raise an exception<br> | |||
end <br> | |||
这是个笨办法,当程序增大时,代码将失去控制,因为我们必须处理每一个 return 和 break,.<br> | |||
为此,我们向"begin...rescue...end"体系中加入了一个关键字 ensure. 无论begin块是否成功,ensure代码域都将执行.<br> | |||
begin<br> | |||
file = open("/tmp/some_file", "w")<br> | |||
# ... write to the file ...<br> | |||
rescue<br> | |||
# ... handle the exceptions ...<br> | |||
ensure<br> | |||
file.close # ... and this always happens.<br> | |||
end <br> | |||
可以只用ensure或只用rescue,但当它们在同一begin...end域中时, rescue 必须放在 ensure前面.<br> | |||
[[category:Ruby学习教程]] | [[category:Ruby学习教程]] |
2009年7月15日 (三) 14:39的最新版本
导航: 上一页 | ASP | PHP | JSP | HTML | CSS | XHTML | aJAX | Ruby | JAVA | XML | Python | ColdFusion
当一个方法结束工作时我们也许需要进行清理工作.也许一个打开的文件需要关闭,缓冲区的数据应清空等等.如果对于每一个方法这里永远只有一个退出点,我们可以心安理得地将我们的清理代码放在一个地方并知道它会被执行;但一个方法可能从多个地方返回,或者因为异常我们的清理代码被意外跳过.
begin
file = open("/tmp/some_file", "w")
# ... write to the file ...
file.close
end
上面,如果在我们写文件的时候发生异常,文件会保留打开.我们也不希望这样的冗余出现:
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"体系中加入了一个关键字 ensure. 无论begin块是否成功,ensure代码域都将执行.
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前面.