0
0
Pythonprogramming~5 mins

Exception chaining in Python

Choose your learning style9 modes available
Introduction

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.

When you want to handle an error but still show the original error that caused it.
When your program catches one error and raises a different error to explain it better.
When debugging complex programs where one error leads to another.
When you want to keep the error history clear for logging or user messages.
Syntax
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.

Examples
This shows how to catch a division error and raise a new error with a clear message.
Python
try:
    x = 1 / 0
except ZeroDivisionError as original_error:
    raise ValueError("Cannot divide by zero") from original_error
Here, a conversion error is caught and a runtime error is raised instead, keeping the original error linked.
Python
try:
    int('abc')
except ValueError as original_error:
    raise RuntimeError("Failed to convert string to int") from original_error
This example shows chaining when a file is missing.
Python
try:
    open('missing_file.txt')
except FileNotFoundError as original_error:
    raise Exception("File not found, please check the filename") from original_error
Sample Program

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.

Python
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__}")
OutputSuccess
Important Notes

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.

Summary

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.