Try Catch Finally block in Ruby

This the ruby code which is equivalent of a try/catch/finally block in other languages.

#Try catch block Syntax

begin
somecode()
rescue
puts “Error #{$!}”
ensure
this_code_will_execute_always()
end

# Sample Code
f = File.open(“testfile.txt”)
begin
# .. process
rescue
# .. handle error
else
puts “– no errors!”
ensure
f.close unless f.nil?
end

Permanent link to this article: https://blog.openshell.in/2011/03/try-catch-finally-block-in-ruby/

Leave a Reply

Your email address will not be published.