Skip to content

“TRY-CATCH-FINALLY” EQUIVALENT IN RUBY

For those like me who are entering the ruby world but have programming experience with other languages, it can be hard to get things done, but that’s a part of ruby, doing things differently :)

On a language like Java or C# the syntax is:

try
{
   some_code();
}
catch(Exeption)
{
   handle_expeption();
}
finally
{
   this_code_is_always_executed();
}

In Ruby the ideia is the same, but the syntax is a little different:
begin – rescue – ensure

Lets see:

 begin
     some_code
 rescue
      handle_error
 ensure
     this_code_is_always_executed
 end

If you need to log the error, you can have access to the error message inside rescue block:

@error_message="#{$!}"

Hope you find it as useful as I did 🙂

Published inBackend

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *