0

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)

2 Answers 2

1

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:

>>> try:
...     try:
...         raise AttributeError('foo')
...     except AttributeError as e:
...         print 'caught', e
... except AttributeError as e:
...     print 'caught the same exception again?', e
... 
caught foo

Only the inner except handler was invoked. If, on the other hand, we re-raise the exception, you'll see both handlers print a message:

>>> try:
...     try:
...         raise AttributeError('foo')
...     except AttributeError as e:
...         print 'caught', e
...         raise e
... except AttributeError as e:
...     print 'caught the same exception again?', e
... 
caught foo
caught the same exception again? foo

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Why not try it out and see what happens with a simple test?

def main():
    try:
        raise ValueError("in main!")
    except ValueError as e:
        print "caught exception",str(e)
        #for fun, re-run with the next line uncommented and see what happens!
        #raise

try:
    main()
except ValueError:
    print "caught an exception above main"

If you actually try this code, you'll notice that it only prints one message (inside the main function) demonstrating that an exception will not propagate upward once caught (unless you re-raise it in your except clause).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.