I have a code sample below, where I want to catch some exception:
in the main function:
try:
...
do_something()
except some_exception,e:
do_some_other_thing
in the do_something function
try:
...
except some_exception,e:
do_some_other_thing
So when I was testing it, I noticed that the exception was handled twice (once in do_somthing(), and once in the main function), is my observation accurate?
Is there a way to catch the exception that are only not captured by its function? Because there are two scenarios that I want to catch and they are somewhat wrapped into the same exception handling class(i.e. some_exception)
Your observation is inaccurate; there must be 2 places that raise
some_exeption, or you are explicitly re-raising it.Once an exception has correctly been caught, it will not be caught by other handlers higher up in the stack.
This is easiest shown with a little demonstration:
Only the inner
excepthandler was invoked. If, on the other hand, we re-raise the exception, you’ll see both handlers print a message:As such, there is no need to have to handle ‘exceptions that are not caught by the function’; you will only need to handle exceptions that were not already caught earlier.