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

我最近开始使用Ruby进行编程,并且正在研究异常处理。


我想知道ensureRuby是否等效finally于C#?我应该有:


file = File.open("myFile.txt", "w")


begin

  file << "#{content} \n"

rescue

  #handle the error here

ensure

  file.close unless file.nil?

end

还是我应该这样做?


#store the file

file = File.open("myFile.txt", "w")


begin

  file << "#{content} \n"

  file.close

rescue

  #handle the error here

ensure

  file.close unless file.nil?

end

不会ensure得到所谓不管,即使一个异常没有什么引发,?


沧海一幻觉
浏览 525回答 3
3回答

慕田峪9158850

仅供参考,即使在本rescue节中再次引发了异常,ensure也会在代码执行继续到下一个异常处理程序之前执行该块。例如:begin&nbsp; raise "Error!!"rescue&nbsp; puts "test1"&nbsp; raise # Reraise exceptionensure&nbsp; puts "Ensure block"end

HUWWW

如果要确保关闭文件,则应使用以下块形式File.open:File.open("myFile.txt", "w") do |file|&nbsp; begin&nbsp; &nbsp; file << "#{content} \n"&nbsp; rescue&nbsp; #handle the error here&nbsp; endend
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Ruby