Ivan Vulović Ivan Vulović - 1 year ago 130
Python Question

Handling all but one exception

How to handle all but one exception ?

except NoChildException:
raise NoChildException

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download