Course contentsShow
← Java
Lesson 767 of 2,87018. Exception Handling FundamentalsFree lesson

Basic Rethrow: throw in catch Block

Learn the syntax for rethrowing a caught exception using the throw keyword inside a catch block.

Basic Rethrow: throw in catch Block

What you'll learn: How to use the throw keyword inside a catch block to pass a caught exception back up the call stack.

Sometimes you need to perform an action when an exception occurs (like logging it or cleaning up a resource), but you don't want to fully handle the exception—you want the caller to deal with it too. This is where rethrowing comes in.

The Core Idea

When you catch an exception, you can immediately throw it again using the throw keyword. The exception reference you receive in the catch parameter becomes the exception object you rethrow.

Syntax:

try {
    // risky code
} catch (SomeException e) {
    // do some local handling (logging, cleanup, etc.)
    throw e;  // rethrow the same exception
}

How It Works

When you write throw e; inside a catch block, the exception continues propagating up the call stack as if you had never caught it—except any code you wrote before the throw statement still executes.

Example:

public void processFile() throws IOException {
    try {
        // code that might throw IOException
    } catch (IOException e) {
        System.out.println("Logging error before rethrowing");
        throw e;  // pass it to the caller
    }
}

Here, you log the error locally but still require the caller to handle the IOException.

Think of It Like This

Imagine a package delivery service. You (the catch block) receive a damaged package (exception). You note the damage in your records, but you still pass it up to your supervisor (the caller) because it's their job to decide what to do next.

Key Takeaway: Use throw e; inside a catch block to perform local actions on an exception while still propagating it up the call stack for further handling.