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

Viewed 42452

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?

5 Answers

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]
Related