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.


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):
return 1 / a, None
except ZeroDivisionError as e:
return None, e

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



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.

    1 / 0
except ZeroDivisionError as e:
    raise Exception('Smelly socks') from e

Or you can use with_traceback.

    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)

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