Java ProgramsExceptionsRethrowing Exception

Rethrowing Exception in Java

intermediate·  Exceptions  ·  Error Handling

Problem

Rethrowing means a catch block does something with an exception — logging it, say — and then uses throw to send that same exception back out, so a caller further up the chain still gets a chance to handle it too.

Catch an exception in one method to log it, then rethrow it so the calling method can also react to the failure.

Input
risky() logs the exception, then rethrows it to main()
Output
Logged: Index 5 out of bounds for length 2 Handled in main: Index 5 out of bounds for length 2

Java Program

Java
public class RethrowingExceptionExample { static void risky() { try { int[] arr = new int[2]; int x = arr[5]; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Logged: " + e.getMessage()); throw e; // sends the same exception back out to the caller } } public static void main(String[] args) { try { risky(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Handled in main: " + e.getMessage()); } } }

Output

Logged: Index 5 out of bounds for length 2 Handled in main: Index 5 out of bounds for length 2

Core Logic

Catching an exception only to log it, then immediately throwing it again with a plain throw e, lets one method observe a failure without being the one responsible for fully handling it.

How It Works
  1. 1risky() wraps its array access in a try-catch, so it gets first look at the exception when it occurs.
  2. 2The catch block prints a log line using e.getMessage(), then executes throw e; to send the exact same exception object back out.
  3. 3Since risky() doesn't fully swallow the exception, its own caller still sees it as if risky() had never caught it at all.
  4. 4main() wraps its call to risky() in its own try-catch, which is where the exception is finally handled for real.
The array access inside risky() throws once; the same exception gets logged inside risky() and then handled again, separately, inside main().
💡

Key Point: The exception object thrown by throw e; is the identical object that was caught — rethrowing doesn't create a new exception, it just lets the same one continue propagating after a method has had a chance to react to it.

Key Concepts

throwcatch and rethrowlogging

Related Programs