Python reraises the same exception won’t work because Once you handle an exception (without re-raising it), the exception, and the accompanying state, are cleared, so there’s no way to access it.
If you want the exception to stay alive, you have to either not handle it, or keep it alive manually.
Python reraises the same exception example
In simple example code running the workers in background threads, the caller won’t see the exception and pass it back manually.
return 1 / a, None
except ZeroDivisionError as e:
return None, e
res, e = worker(0)
How do I raise the same Exception with a custom message in Python?
Answer: We can chain the exceptions using raise from.
try: 1 / 0 except ZeroDivisionError as e: raise Exception('Smelly socks') from e
Or you can use with_traceback.
try: 1 / 0 except ZeroDivisionError as e: raise Exception('Smelly socks').with_traceback(e.__traceback__)
Do comment if you have any doubts or suggestions on this Python exception topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.