133

I know of the standard technique of having a begin <some code> rescue <rescue code> 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?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Sid
  • 6,134
  • 9
  • 34
  • 57

5 Answers5

254

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

def foo
  ...
rescue
  ...
end
alex.zherdev
  • 23,914
  • 8
  • 62
  • 56
52

You can also rescue inline:

1 + "str" rescue "EXCEPTION!"

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

peku
  • 5,003
  • 3
  • 20
  • 15
28

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.
  • 1,327
  • 8
  • 11
22

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
Hieu Le
  • 2,106
  • 1
  • 23
  • 23
5

Bonus! You can also do this with other sorts of blocks. E.g.:

[1, 2, 3].each do |i|
  if i == 2
    raise
  else
    puts i
  end
rescue
  puts 'got an exception'
end

Outputs this in irb:

1
got an exception
3
 => [1, 2, 3]
Purplejacket
  • 1,808
  • 2
  • 25
  • 43