“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();
}

On 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 ;)

2 thoughts on ““Try-Catch-Finally” equivalent in Ruby”

  1. if i want to catch or pick the element which got failed, in a report. In java we to to catch using printstacktrace n all type methods. Do we have anything in ruby to do this. I want to catch the element which got failed while running my ruby script.

Leave a Reply

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

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>