为了账号安全,请及时绑定邮箱和手机立即绑定

开始,营救和确保使用Ruby?

开始,营救和确保使用Ruby?

沧海一幻觉 2019-11-21 10:34:02
我最近开始使用Ruby进行编程,并且正在研究异常处理。我想知道ensureRuby是否等效finally于C#?我应该有:file = File.open("myFile.txt", "w")begin  file << "#{content} \n"rescue  #handle the error hereensure  file.close unless file.nil?end还是我应该这样做?#store the filefile = File.open("myFile.txt", "w")begin  file << "#{content} \n"  file.closerescue  #handle the error hereensure  file.close unless file.nil?end不会ensure得到所谓不管,即使一个异常没有什么引发,?
查看完整描述

3 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

仅供参考,即使在本rescue节中再次引发了异常,ensure也会在代码执行继续到下一个异常处理程序之前执行该块。例如:


begin

  raise "Error!!"

rescue

  puts "test1"

  raise # Reraise exception

ensure

  puts "Ensure block"

end


查看完整回答
反对 回复 2019-11-21
?
HUWWW

TA贡献1874条经验 获得超12个赞

如果要确保关闭文件,则应使用以下块形式File.open:


File.open("myFile.txt", "w") do |file|

  begin

    file << "#{content} \n"

  rescue

  #handle the error here

  end

end


查看完整回答
反对 回复 2019-11-21
  • 3 回答
  • 0 关注
  • 518 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信