Exception chaining helps you keep track of errors that happen one after another. It shows the original error and the new error together, so you understand what caused the problem.
Exception chaining in Python
try: # code that may cause an error except SomeError as original_error: raise NewError("Explanation") from original_error
The from keyword links the new error to the original error.
This helps Python show both errors in the error message.
try: x = 1 / 0 except ZeroDivisionError as original_error: raise ValueError("Cannot divide by zero") from original_error
try: int('abc') except ValueError as original_error: raise RuntimeError("Failed to convert string to int") from original_error
try: open('missing_file.txt') except FileNotFoundError as original_error: raise Exception("File not found, please check the filename") from original_error
This program tries to divide two numbers. If the denominator is zero, it catches the division error and raises a new error with a clearer message. It then prints both the new error and the original error.
def divide_numbers(numerator, denominator): try: result = numerator / denominator except ZeroDivisionError as original_error: raise ValueError("You tried to divide by zero, which is not allowed.") from original_error return result try: print(divide_numbers(10, 0)) except ValueError as error: print(f"Caught an error: {error}") print(f"Original error was: {error.__cause__}")
Exception chaining helps keep the error history clear and easy to understand.
Time complexity is not affected by exception chaining; it only adds clarity to error messages.
Common mistake: forgetting to use from causes the original error to be lost.
Use exception chaining when you want to add context to errors without hiding the original cause.
Exception chaining links a new error to the original error using raise ... from ....
This helps you see the full story of what went wrong in your program.
It is useful for debugging and making error messages clearer.