ruby 异常处理:ensure
来源:互联网 发布:js 数组排序函数 编辑:程序博客网 时间:2024/06/04 19:49
当一个方法结束工作时我们也许需要进行清理工作.也许一个打开的文件需要关闭,缓冲区的数据应清空等等.如果对于每一个方法这里永远只有一个退出点,我们可以心安理得地将我们的清理代码放在一个地方并知道它会被执行;但一个方法可能从多个地方返回,或者因为异常我们的清理代码被意外跳过.
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
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前面
转自:http://www.codesky.net/article/201112/122275.html
0 0
- ruby 异常处理:ensure
- ruby 异常处理:ensure
- Ruby中用begin/end …rescue…ensure … raise 来处理异常
- ruby的异常处理
- Ruby 异常处理
- ruby异常处理
- ruby异常处理
- ruby异常处理
- Ruby 异常处理
- ruby中的异常处理
- ruby 異常處理:ensure
- ruby编程中的异常处理
- ruby学习笔记(9)--异常处理
- Ruby学习笔记_异常处理rescue
- Ruby 异常
- ruby ROR中异常处理rescue与raise介绍
- Ruby学习笔记4(范围,迭代器,异常处理)
- ruby on rails 异常
- 吴怀宇老师【数字智能三篇】
- 修改用户名后操作view 报1449 错误
- Java中的main()方法详解
- iReport做报表 java.lang.ClassNotFoundException: net.sf.jasperreports.compilers.GroovyEvaluator
- 配置 Rails 应用程序
- ruby 异常处理:ensure
- java_io.FileReaderStream
- ext store
- android ListView几个比较特别的属性
- js实现数据库与网页之间的换行互转
- ORACLE的Copy命令和create table,insert into的比较
- java 注册表工具类
- typedef
- IOS开发之dispatch_once创建单例