页面导航: 首页脚本专栏ruby专题 → 正文内容

ruby 异常处理:ensure

发布:dxy 字体:[增加 减小] 类型:转载
 当一个方法结束工作时我们也许需要进行清理工作.也许一个打开的文件需要关闭,缓冲区的数据应清空等等.如果对于每一个方法这里永远只有一个退出点,我们可以心安理得地将我们的清理代码放在一个地方并知道它会被执行;但一个方法可能从多个地方返回,或者因为异常我们的清理代码被意外跳过.
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 异常处理:ensure内容,或者用Google搜索相关更多
浏览次数:载入中... 打印本文关闭本文返回首页

文章评论

共有 位脚本之家网友发表了评论我来说两句

同 类 文 章
最 近 更 新
热 点 排 行