ruby异常处理:ensure
2023-06-13 09:13:58 时间
当一个方法结束工作时我们也许需要进行清理工作.也许一个打开的文件需要关闭,缓冲区的数据应清空等等.如果对于每一个方法这里永远只有一个退出点,我们可以心安理得地将我们的清理代码放在一个地方并知道它会被执行;但一个方法可能从多个地方返回,或者因为异常我们的清理代码被意外跳过.
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前面.
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前面.
相关文章
- 【Ruby高级技术】在项目中使用多线程之后的一系列问题解决方案-同步控制、异常处理、死锁处理
- .NET/ASP.NET/C#/WCF/SQL Server/My SQL/Java/JSP/JDBC/Spring/Spring MVC/PHP/Python/Ruby/Shell/Agile/CSS/HTML/HTTP/Unix/Linux大量PDF书籍/电子书籍下载, Effective Java 下载详解编程语言
- Linux系统下Ruby版本的升级(linux升级ruby)
- Linux下Ruby软件卸载指南(linuxruby卸载)
- 「Linux上安装Ruby的指南」(linux安装ruby)
- Connecting Ruby to MySQL: A Comprehensive Guide for Developers(ruby连接mysql)
- Ruby开发灵活的MSSQL应用(ruby mssql)
- 快速下载MySQLRuby,为Ruby开发提供强大支持(mysql_ruby下载)
- Ruby环境下Redis的快速安装(ruby redis安装)
- 火热的Redis与灵活的Ruby开启一场有趣的运算旅程(redis跟ruby)
- Ruby入门点滴-Ruby的安装
- 什么是ruby和Ruby概述
- 解析ruby全局变量
- Ruby中的Range对象学习笔记
- Ruby字符串、条件、循环、数组、Hash、类基本操作笔记
- Ruby中字符串左侧补零方法实例
- ruby元编程实际使用实例
- Ruby中的类GoogleMap/Reduce框架Skynet介绍
- Ruby中的Mechanize的使用教程
- Ruby中使用mechanize批量下载校内网相册照片