How does one use rescue in Ruby without the begin and end block

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!


Example:

begin
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end

Here, def as a begin statement:

def
  # something which might raise an exception
rescue SomeExceptionClass => some_variable
  # code that deals with some exception
ensure
  # ensure that this code always runs
end

You can also rescue inline:

1 + "str" rescue "EXCEPTION!"

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


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

def foo
  ...
rescue
  ...
end

Tags:

Ruby