3

I'm learning about exception handling in python and am a little stumped how exactly the context attribute works, or at least why the code I have written produces the outcome it does. My understanding is that when an exception,E, is raised implicitly during the handling of another exception,P, the exception's E context attribute will store a reference to P.

So I have set up the following code:

def g():
    try: 1/0
    except Exception as E:
        print('E context', E.__context__)
        try: raise Exception
        except Exception as J:
                print('J context', J.__context__)
                try: raise Exception
                except Exception as M:
                    print('M context', M.__context__)
                    try: raise Exception
                    except Exception as T:
                        print('T context', T.__context__)

The output I get is:

E context None

J context division by zero

M context

T context

What I was expecting to see was M context and T context to have references to previous exceptions, but that doesn't seem to be the case. Would appreciate knowing where I am going wrong on my thinking on this.

1 Answer 1

4

Since you raised a blank exception, print(M.__context__) outputs an empty string (because str(Exception()) is an empty string).

Consider this:

try:
    1/0
except Exception as E:
    print('E context', E.__context__)
    try:
        raise Exception('non blank 1')
    except Exception as J:
        print('J context', J.__context__)
        try:
            raise Exception('non blank 2')
        except Exception as M:
            print('M context', M.__context__)

Outputs

E context None
J context division by zero
M context non blank 1
Sign up to request clarification or add additional context in comments.

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.