Home / Backend / 1 min read • 2011-05-10

“TRY-CATCH-FINALLY” EQUIVALENT IN RUBY

🚀
Carlos Rodrigues
Full Stack Engineer

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 🙂

Comments (0)

No comments yet. Be the first to share your thoughts!

Leave a Comment