Skip to content

Python reraise same exception

  • by

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.

Source: https://stackoverflow.com/questions/51197783/

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.

def worker(a):
try:
return 1 / a, None
except ZeroDivisionError as e:
return None, e


def master():
res, e = worker(0)
if e:
print(e)
raise e

master()

Output:

Python reraise same exception

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__)

Source: https://stackoverflow.com/questions/9157210

Do comment if you have any doubts or suggestions on this Python exception topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading