Raise an Exception to another Exception in Python
In this tutorial, we will learn how to raise an exception in response to another exception in Python. This is also called exception chaining.
In the below example code, we have a try-except block. The try block contains a statement with ZeroDivisionError. This is handled in the except block and in response, the RuntimeError is thrown as we used a raise from statement as shown below. Have a look at the code.
try: a = 5/0 except ZeroDivisionError as e: raise RuntimeError('Error') from e
Output:
Traceback (most recent call last): File "err.py", line 2, in <module> a = 5/0 ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "err.py", line 4, in <module> raise RuntimeError('Error') from e RuntimeError: Error
Chained Exception can also occur when a statement in the except block contains an error as shown in the given code. This is an example of implicit exception chaining.
try: a = 5/0 except ZeroDivisionError as e: print(b)
Output:
Traceback (most recent call last): File "err.py", line 2, in <module> a = 5/0 ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "err.py", line 4, in <module> print(b) NameError: name 'b' is not defined
We can prevent exception chaining using raise from None statement. The below code demonstrates how we can suppress exception chaining.
try: a = 5/0 except ZeroDivisionError: raise RuntimeError('Error') from None
Output:
Traceback (most recent call last): File "err.py", line 4, in <module> raise RuntimeError('Error') from None RuntimeError: Error
Thank you.
Also read: Handling Exceptions using try and except in Python 3.x. or earlier
Leave a Reply