How to handle all but one exception?
try:
something
except <any Exception except for a NoChildException>:
# handling
Something like this, except without destroying the original traceback:
try:
something
except NoChildException:
raise NoChildException
except Exception:
# handling
I found a context in which catching all errors but one is not a bad thing, namely unit testing.
If I have a method:
Then it could plausibly have a unit test that looks like:
Because you have now detected that my_method just threw an unexpected exception.
I'd offer this as an improvement on the accepted answer.
This approach improves on the accepted answer by maintaining the original stacktrace when MySpecialException is caught, so when your top-level exception handler logs the exception you'll get a traceback that points to where the original exception was thrown.
The answer is to simply do a bare
raise
:This will re-raise the last thrown exception, with original stack trace intact (even if it's been handled!).