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?
Yes,
ensure
is called in any circumstances. For more information see "Exceptions, Catch, and Throw" of the Programming Ruby book and search for "ensure".