Introduction
Exceptions can be raised by a developer or programmer when they deem it necessary. It allows us to forcefully throw the exception we require along with a message of our choice. Exception chaining is a method that involves raising an exception to another exception. This is done when we want to include information about two different exceptions that may occur.
You can also read about the Multilevel Inheritance in Python and Convert String to List Python.
Examples
In the following example, a runtime error is raised inside the exception handler for ZeroDivisionError. This displays the information of both the errors that occurred during execution.
try:
a = 10/0
except ZeroDivisionError as e:
raise RuntimeError('Error') from e
Output:
Traceback (most recent call last):
File "main.py", line 2, in <module>
a = 10/0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 4, in <module>
raise RuntimeError('Error') from e
RuntimeError: Error
Exception chaining can also be caused if there is an exception in the except block itself. This is an implicit form of exception chaining. Observe the example shown below.
try:
a = 5/0
except ZeroDivisionError as e:
print(err)
Output:
Traceback (most recent call last):
File "main.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 "main.py", line 4, in <module>
print(b)
NameError: name 'err' is not defined
We can suppress exception chaining by raising the other exception from None. Here is an example.
try:
a = 5/0
except ZeroDivisionError as e:
raise RuntimeError('Error') from None
Output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
raise RuntimeError('Error') from None
RuntimeError: Error
You can practice by yourself with the help of online python compiler.