21

In Ruby, is it possible to rescue all exceptions except for a specified one?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

3 Answers3

54
begin

rescue MyException
  raise #to reraise the same exception without changing it
rescue Exception => e
  #do something with e
end
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
12

Not as such no. But you can rescue all exceptions and reraise the exception if it is a MyException.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • You're not supposed to rescue all exceptions: https://stackoverflow.com/questions/10048173/why-is-it-a-bad-style-to-rescue-exception-e-in-ruby – Will Sheppard Jun 13 '17 at 10:14
  • 1
    @WillSheppard I would argue that this depends entirely on what your code is doing. – Orlando May 31 '21 at 20:16
2

Without knowing more about your problem, I'd suggest Ken Bloom's answer.

However, I'd like to know more about why you're doing it.

Are you worried about a really severe exception, and not wanting to rescue that one, but allow less severe exceptions to be rescued?

In that case, I'd make my custom exception inherit from Exception rather than StandardError and then have

begin
  do_risky_stuff
rescue # Not rescue Exception
  handle_less_serious_stuff
end
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338