我最近开始用Ruby编程,我正在研究异常处理。 编程
我想知道是否ensure
是finally
在C#中的Ruby等价物? 我应该: less
file = File.open("myFile.txt", "w") begin file << "#{content} \n" rescue #handle the error here ensure file.close unless file.nil? end
或者我应该这样作? spa
#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
不管如何都被调用,即便没有引起异常? code
仅供参考,即便在rescue
部分从新引起异常,也会在代码执行继续执行下一个异常处理程序以前执行ensure
阻止。 例如: 资源
begin raise "Error!!" rescue puts "test1" raise # Reraise exception ensure puts "Ensure block" end
这就是咱们须要ensure
: get
def hoge begin raise rescue raise # raise again ensure puts 'ensure' # will be executed end puts 'end of func' # never be executed end
是的, ensure
在任何状况下都被调用。 有关更多信息,请参阅编程Ruby书籍的“ 异常,捕获和抛出 ”并搜索“确保”。 io
若是要确保文件已关闭,则应使用File.open
的块形式: test
File.open("myFile.txt", "w") do |file| begin file << "#{content} \n" rescue #handle the error here end end
是的, ensure
finally
保证块将被执行 。 这对于确保关键资源受到保护很是有用,例如在出错时关闭文件句柄或释放互斥锁。 书籍