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

Implementing Error Propagation Strategies

Decide when to handle an exception locally and when to propagate it to the caller for centralized error management.

In this lesson, you will learn how to decide whether to resolve an error immediately or pass it up the call stack to a higher-level manager.

When to Handle Locally

You should handle an exception locally when your function has enough context to "fix" the problem or perform a meaningful fallback. For example, if a function attempts to load a configuration file and you have a safe default setting to use if the file is missing, you should catch the FileNotFoundError inside that function and provide the default.

def get_config():
    try:
        with open("config.json") as f:
            return f.read()
    except FileNotFoundError:
        # We can fix this locally!
        return '{"theme": "default"}'

When to Propagate

You should propagate an exception when your function cannot possibly know how to handle the error. If a function is responsible for calculating a user’s balance but a database connection fails, the function doesn't know whether to retry, show an error to the user, or log the event to a monitoring service. By letting the exception bubble up to the caller, you allow a higher-level "controller" to decide the appropriate action.

Propagating is as simple as not catching the error. Alternatively, you can use raise from to add context while still ensuring the caller receives the signal that something went wrong.

def update_balance(user_id, amount):
    # If the database fails, we don't catch it here.
    # We let the caller decide how to notify the user.
    db.execute("UPDATE balances SET amount = ? WHERE id = ?", (amount, user_id))

def run_app():
    try:
        update_balance(1, 100)
    except DatabaseError:
        print("System is temporarily unavailable. Please try again later.")

By keeping low-level functions focused on their specific tasks and leaving high-level decision-making to the "top" of your application, you create a cleaner, more maintainable flow. Handling every error at the lowest level often leads to redundant code, while propagating them too far can make it difficult to trace the original cause.

Key Takeaway: Handle errors locally when you can offer a resolution; propagate errors when the caller is better equipped to decide how to respond.