Course contentsShow
← Python
Lesson 349 of 1,0606. Error Handling and File I/OFree lesson

Implementing Exception Chaining with Raise From

Use the 'from' keyword to preserve the original traceback when wrapping low-level errors in higher-level custom exceptions.

Implementing Exception Chaining with Raise From

In this lesson, you will learn how to preserve the full history of an error by chaining exceptions using the from keyword.

The Problem: Losing the "Why"

When you write a program, you often catch a low-level technical error (like a FileNotFoundError) and choose to raise a more descriptive, high-level custom exception to help the user understand what went wrong in the context of your application.

However, if you simply raise your custom exception inside a try-except block, Python creates a new traceback. The original error—the root cause—is discarded. This makes debugging difficult because you lose sight of the technical trigger that led to your custom error.

The Solution: The from Keyword

Python provides the raise ... from syntax to explicitly link a new exception to the one that caused it. This creates a "chain" in the traceback, showing both your high-level error and the low-level cause.

Consider this example where we process a configuration file:

class ConfigurationError(Exception):
    """Custom exception for app-specific errors."""
    pass

def load_config():
    try:
        with open("missing_config.json", "r") as f:
            data = f.read()
    except FileNotFoundError as e:
        # We wrap the low-level error in our custom exception
        raise ConfigurationError("Failed to initialize application settings.") from e

In the code above, the from e part tells Python, "This ConfigurationError was triggered by this specific FileNotFoundError."

When this program runs, the traceback will display your custom message followed by a line saying The above exception was the direct cause of the following exception:. This tells the developer exactly what happened at the system level while keeping the interface clean for the user.

If you ever want to suppress the traceback entirely (hiding the original error chain), you can use raise NewException() from None, though you should use this sparingly as it obscures important debugging information.

Key Takeaway: Always use raise CustomException(...) from e to preserve the original traceback, ensuring that the root cause of an error remains visible during debugging.