Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exception handling context attribute

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.

like image 393
mishlke Avatar asked Jul 17 '26 19:07

mishlke


1 Answers

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
like image 120
DeepSpace Avatar answered Jul 20 '26 08:07

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!