Ivan Vulović Ivan Vulović - 7 months ago 55
Python Question

Handling all but one exception

How to handle all but one exception ?

except NoChildException:
raise NoChildException


The answer is to simply do raise:

except SomeException:

raise without any expression after it will simple raise the last thrown exception (even if it's been handled!). It's roughly equivalent to:

except SomeException as e:
    raise e

If you think another exception might be thrown in the catch block (obviously impossible in this case), you should use the latter format to ensure you re-raise the right exception.

However, as noted in my comment:

Simple answer: Don't. It's really bad practice to catch all exceptions, as you will tend to catch ones you didn't mean to, obscuring errors. There are only a tiny number of legitimate cases for doing such a thing.

Just catch the errors that you think your code might throw, and you know how to handle, and leave any others. If anything else happens, your program will then exit out - which is what you want, as you can then see why it occurred and handle it correctly.