Is ensure in Ruby = finally the same in C#?
I don't know exactly when sense will run, so I don't know when to close the file.
file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
rescue
#handle the error here
ensure
file.close unless file.nil?
end
file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
file.close
rescue
#handle the error here
ensure
file.close unless file.nil?
end
sense literally means "guarantees that the code will always be valued." It's the same as Java/C#'s finally.
Usually, the flow of exception handling begin-resue-else-sense-end flows like this
begin
# code that may or may not be exception
rescue SomeExceptionClass => some_variable
# Code that handles what excpetion
rescue SomeOtherException => some_other_variable
# Code that handles another excpetion
else
# Code to run if exception is not raised
ensure
# Code to be executed unconditionally with or without exception
end
In the flow above, resue, ense, and else are not required, and are written optionally if necessary.
The => var part is not necessarily required in resue, but if left blank, it will be difficult to determine exactly what exceptions have occurred.
If exception class is not specified in rescue, all exceptions that inherit StandardError will be filtered (SystemStackError that does not inherit StandardError, etc. will be excluded
In ruby, certain blocks are also exception blocks. For example, defining a method is also an exception block. Code 1 below can be replaced by Code 2 and Code 3.
Code 1
def foo
begin
# ...
rescue
# ...
end
end
Code 2
def foo
# ...
rescue
# ...
end
Code 3
def foo
# ...
ensure
# ...
end
(Same class/module definition)
© 2026 OneMinuteCode. All rights reserved.