tags:

views:

644

answers:

3

I know of the standard technique of having a begin rescue end

How does one just use the rescue block on its own.

How does it work and how does it know which code is being monitored?

+7  A: 

A method "def" can serve as a "begin" statement:

def foo
  ...
rescue
  ...
end
neutrino
neat ... did not know that one.
Toby Hede
Thanks I just wanted to know how that works. Thats pretty much what I was looking for. Thank you.
Sid
+6  A: 

You can also rescue inline:

1 + "str" rescue "EXCEPTION!"

will print out "EXCEPTION!" since 'String can't be coerced into Fixnum'

peku
+4  A: 

I'm using the def / rescue combination a lot with ActiveRecord validations:

def create
   @person = Person.new(params[:person])
   @person.save!
   redirect_to @person
rescue ActiveRecord::RecordInvalid
   render :action => :new
end

I think this is very lean code!

Edwin V.