What is the difference between cause and context? - Stack Overflow
I found three cool new dunders related to exceptions
- __cause__
is the cause of the exception - due to the given exception, the current exception was raised. This is a direct link - X threw this exception, therefore Y has to 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 handled at the time this one was raised. This is so that you don’t loose the fact that the other exceptions happened (and hence were at this code to throw the exception) - the context. X threw this exception, while handling it, Y was also thrown.
- __traceback__
shows you the stack - the various levels of functions that have been followed to get to the current line of code. This allows you to pinpoint what caused the exception. It is likely to be used (potentially in tandem with __context__
) to find what caused a given bug.
The __cause__
parameter implicitly happens as follows:
try:
...
except ExceptionA as exc:
raise ExceptionB from exc
This will create two stack traces, one referring the other via __cause__
.