22

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

3 Answers 3

55
begin rescue MyException raise #to reraise the same exception without changing it rescue Exception => e #do something with e end 
Sign up to request clarification or add additional context in comments.

Comments

12

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

2 Comments

You're not supposed to rescue all exceptions: stackoverflow.com/questions/10048173/…
@WillSheppard I would argue that this depends entirely on what your code is doing.
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.