Begin, Rescue and Ensure in Ruby?

2019-01-03 07:08发布

I've recently started programming in Ruby, and I am looking at exception handling.

I was wondering if ensure was the Ruby equivalent of finally in C#? Should I have:

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

begin
  file << "#{content} \n"
rescue
  #handle the error here
ensure
  file.close unless file.nil?
end

or should I do this?

#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

Does ensure get called no matter what, even if an exception isn't raised?

7条回答
淡お忘
2楼-- · 2019-01-03 07:53

Yes, ensure is called in any circumstances. For more information see "Exceptions, Catch, and Throw" of the Programming Ruby book and search for "ensure".

查看更多
登录 后发表回答