raising an Exception in an Except without calling the original Exception<>
This question already has an answer here:
- Python print last traceback only? 1 answer
Quoting the docs:
When raising (or re-raising) an exception in an except or finally clause __context__ is automatically set to the last exception caught; if the new exception is not handled the traceback that is eventually displayed will include the originating exception(s) and the final exception.
This is exactly your case:
try: try: raise ValueError except ValueError: raise TypeError except Exception as e: print('Original:', type(e.__context__)) # Original: <class 'ValueError'> print('Explicitly raised:', type(e)) # Explicitly raised: <class 'TypeError'>
There's only one active exception; I might have written except TypeError instead of except Exception and the output would still be the same.
If you want to prevent Python from printing the original exception, use raise ... from None:
try: raise ValueError except ValueError: raise TypeError from None