What is the difference between __cause__ and __context__?

These are attributes for Python exceptions, but I am having trouble wrapping around them. The Python documentation seems pretty calm. I looked through the documentation, but rather confused. So what is the difference between them and how are they used?

EDIT: In this note, how are they related to __traceback__ , if at all?

EDIT 3: I guess I just don't understand __cause__ . I finally understand __traceback__ and __context__ . Why is attribute_error.__cause__ not related to AttributeError() ?

 try: raise NameError() from OSError except NameError as name_error: print('name_error.__cause__: %s' % repr(name_error.__cause__)) print('name_error.__context__: %s' % repr(name_error.__context__)) print('name_error.__traceback__: %s' % repr(name_error.__traceback__)) try: raise AttributeError() except AttributeError as attribute_error: print('attribute_error.__cause__: %s' % repr(attribute_error.__cause__)) print('attribute_error.__context__: %s' % repr(attribute_error.__context__)) print('attribute_error.__traceback__: %s' % repr(attribute_error.__traceback__)) raise attribute_error from IndexError 

Displays

 name_error.__cause__: OSError() name_error.__context__: None name_error.__traceback__: <traceback object at 0x000000000346CAC8> attribute_error.__cause__: None attribute_error.__context__: NameError() attribute_error.__traceback__: <traceback object at 0x000000000346CA88> Traceback (most recent call last): File "C:\test\test.py", line 13, in <module> raise attribute_error from IndexError File "C:\test\test.py", line 8, in <module> raise AttributeError() AttributeError 
+4
source share
1 answer

__cause__ is the cause of the exception - because of this exception, the current exception has been raised. This is a direct link - X threw this exception, so Y should throw this exception.

__context__ , on the other hand, means that the current exception was raised while trying to handle another exception and defines the exception that was being processed at the time it was raised. This is so that you won’t lose the fact that other exceptions occurred (and therefore were in this code to throw an exception) - the context. X threw this exception, and when it was processed, Y was also thrown.

__traceback__ shows you the stack β€” various levels of functions that were executed to jump to the current line of code. This allows you to determine what caused the exception. It will probably be used (potentially in tandem with __context__ ) to find the cause of this error.

+6
source

All Articles