Skip to lesson

Rethrow and wrap checked exceptions

Sometimes a method catches an exception only to add something and send it on. Rethrowing passes the same exception object up to the caller; wrapping throws a new exception, often an unchecked one, with the original kept as its cause.

Rethrowing the same exception after a log line

Rethrowing means catching an exception and throwing the same object again with throw e;. The method must still declare the checked type in its throws clause, because the exception still leaves it.

Example 1 · Log a line, then rethrow

LogAndRethrowDemo.javaJava
import java.io.IOException;
public class LogAndRethrowDemo {    static void sendReceipt(String roll) throws IOException {        if (roll.startsWith("EE")) {            throw new IOException("mail server rejected the message");        }        System.out.println("receipt sent to " + roll);    }
    static void uploadFee(String roll) throws IOException {        try {            sendReceipt(roll);        } catch (IOException e) {            System.out.println("[uploadFee] failed for " + roll + ": " + e.getMessage());            throw e;   // same object, the caller decides        }    }
    public static void main(String[] args) {        String[] rolls = {"CS101", "EE205"};        for (String roll : rolls) {            try {                uploadFee(roll);            } catch (IOException e) {                System.out.println("main: please retry later for " + roll);            }        }    }}
Output
receipt sent to CS101
[uploadFee] failed for EE205: mail server rejected the message
main: please retry later for EE205

What this code does

  • uploadFee adds the roll number to the log, which sendReceipt's message does not have, and then throw e; passes the very same exception on.
  • Because the exception still leaves uploadFee, the method keeps throws IOException, and main makes the real decision: ask the student to retry.

Use it when this method has something to add, such as a log line with the roll number it was working on, but cannot decide what to do; the caller must. The stack trace is not changed: it still points to where the exception was first created.

Log in one place only. If every layer logs and rethrows, one failure appears three or four times in the log, and people stop trusting it. Usually the code that finally handles the exception logs it.

Precise rethrow with a final catch parameter

Precise rethrow (Java 7) lets you catch a broad type such as Exception and still declare only the checked exceptions the try can really throw.

Example 2 · Precise rethrow keeps the exact types

PreciseRethrowDemo.javaJava
import java.io.IOException;
public class PreciseRethrowDemo {    static void allotRoom(String room) throws IOException, InterruptedException {        try {            if (room.isEmpty()) {                throw new IOException("room list file is empty");            }            if (room.equals("WAIT")) {                throw new InterruptedException("allotment queue stopped");            }            System.out.println("allotted " + room);        } catch (Exception e) {      // one log line for every problem            System.out.println("log: " + e.getClass().getSimpleName() + " while allotting '" + room + "'");            throw e;                 // e is never reassigned: precise rethrow        }    }
    public static void main(String[] args) {        String[] rooms = {"B-104", "", "WAIT"};        for (String room : rooms) {            try {                allotRoom(room);            } catch (IOException e) {                System.out.println("main: file problem - " + e.getMessage());            } catch (InterruptedException e) {                System.out.println("main: stopped - " + e.getMessage());            }        }    }}
Output
allotted B-104
log: IOException while allotting ''
main: file problem - room list file is empty
log: InterruptedException while allotting 'WAIT'
main: stopped - allotment queue stopped

What this code does

  • The catch (Exception e) block is shared, but allotRoom declares only IOException, InterruptedException. The compiler sees that the try can throw only those two checked types.
  • So main can still catch the two types separately. Without precise rethrow, allotRoom would need throws Exception, and every caller would have to catch plain Exception.

Example 3 · Assigning to the catch variable breaks it

ReassignRethrowDemo.javaJava
import java.io.IOException;
public class ReassignRethrowDemo {    static void allotRoom(String room) throws IOException, InterruptedException {        try {            if (room.isEmpty()) {                throw new IOException("room list file is empty");            }            Thread.sleep(10);            System.out.println("allotted " + room);        } catch (Exception e) {            if (e instanceof IOException) {                e = new IOException("hostel office: " + e.getMessage());            }            throw e;        }    }
    public static void main(String[] args) throws Exception {        allotRoom("B-104");    }}
Sample compiler output
ReassignRethrowDemo.java:15: error: unreported exception Exception; must be caught or declared to be thrown
            throw e;
            ^
1 error

What this code does

  • The line e = new IOException(...) makes e no longer effectively final, so throw e; now counts as throwing plain Exception, which the method does not declare.
  • Fix: leave e alone and throw a new variable instead, for example throw new IOException("hostel office: " + e.getMessage(), e); inside the if.

If the try can throw only IOException and InterruptedException, then catch (Exception e) { ...; throw e; } needs only throws IOException, InterruptedException, not throws Exception.

This works only while the catch variable is effectively final: you never assign a new value to e. Once you write e = ..., the compiler can no longer be sure what e holds, and treats throw e; as throwing plain Exception.

Wrapping in UncheckedIOException or a RuntimeException

UncheckedIOException (Java 8) is an unchecked exception made to carry an IOException as its cause: throw new UncheckedIOException("could not read photo", e);. For other checked exceptions, wrap in RuntimeException or your own unchecked class, again passing e as the cause.

Example 4 · Wrap inside a Comparator, unwrap outside

WrapUncheckedDemo.javaJava
import java.io.IOException;import java.io.UncheckedIOException;import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class WrapUncheckedDemo {    // stands in for reading the size of a student's photo from disk    static long photoSize(String roll) throws IOException {        if (roll.endsWith("X")) {            throw new IOException("photo missing for " + roll);        }        return roll.length() * 100L;    }
    static long photoSizeUnchecked(String roll) {        try {            return photoSize(roll);        } catch (IOException e) {            throw new UncheckedIOException("cannot sort photos", e);        }    }
    public static void main(String[] args) {        List<String> rolls = new ArrayList<>(List.of("CS1012", "CS7", "CS45"));        rolls.sort(Comparator.comparingLong(WrapUncheckedDemo::photoSizeUnchecked));        System.out.println("sorted: " + rolls);
        rolls.add("CS9X");        try {            rolls.sort(Comparator.comparingLong(WrapUncheckedDemo::photoSizeUnchecked));        } catch (UncheckedIOException e) {            IOException original = e.getCause();            System.out.println(e.getMessage() + " <- " + original.getMessage());        }    }}
Output
sorted: [CS7, CS45, CS1012]
cannot sort photos <- photo missing for CS9X

What this code does

  • comparingLong needs a function that cannot throw checked exceptions, so photoSize cannot be used directly. photoSizeUnchecked wraps the IOException in an UncheckedIOException.
  • Outside the sort, e.getCause() gives the original IOException, already typed, with no cast. Nothing about the original problem was lost.

Wrap when a checked exception cannot legally leave the method. The usual case is code inside an interface method that declares no checked exceptions, such as Comparator.compare, Runnable.run or a lambda for a stream. Wrap also when no caller could do anything better than stop. Unwrapping is easy, because nothing is lost. UncheckedIOException.getCause() returns the original IOException, already typed as IOException.

Checked exceptions inside lambdas and streams

The functional interfaces used by streams, such as Function, Predicate and Consumer, declare no checked exceptions. So a lambda passed to map cannot throw IOException, and throws IOException on the outer method does not help: the lambda body is a separate method.

Example 5 · A checked exception inside map

LambdaCheckedDemo.javaJava
import java.io.IOException;import java.util.List;
public class LambdaCheckedDemo {    static int readMarks(String roll) throws IOException {        if (roll.isEmpty()) {            throw new IOException("empty roll number");        }        return 60 + roll.length();    }
    public static void main(String[] args) throws IOException {        List<String> rolls = List.of("CS101", "CS102");        List<Integer> marks = rolls.stream().map(r -> readMarks(r)).toList();        System.out.println(marks);    }}
Sample compiler output
LambdaCheckedDemo.java:14: error: unreported exception IOException; must be caught or declared to be thrown
        List<Integer> marks = rolls.stream().map(r -> readMarks(r)).toList();
                                                               ^
1 error

What this code does

  • map takes a Function, whose apply method declares no checked exceptions, so the lambda body may not throw IOException.
  • main already says throws IOException, but that does not help: the lambda is a separate method, and the rule applies to it on its own.

Example 6 · Wrap in the stream, unwrap at the edge

StreamWrapDemo.javaJava
import java.io.IOException;import java.io.UncheckedIOException;import java.util.List;
public class StreamWrapDemo {    static int readMarks(String roll) throws IOException {        if (roll.isEmpty()) {            throw new IOException("empty roll number");        }        return 60 + roll.length();    }
    static int readMarksUnchecked(String roll) {        try {            return readMarks(roll);        } catch (IOException e) {            throw new UncheckedIOException(e);        }    }
    // callers still see an honest checked exception    static List<Integer> readAll(List<String> rolls) throws IOException {        try {            return rolls.stream().map(StreamWrapDemo::readMarksUnchecked).toList();        } catch (UncheckedIOException e) {            throw e.getCause();        }    }
    public static void main(String[] args) {        try {            System.out.println(readAll(List.of("CS101", "CS7")));            System.out.println(readAll(List.of("CS101", "", "CS9")));        } catch (IOException e) {            System.out.println("main caught IOException: " + e.getMessage());        }    }}
Output
[65, 63]
main caught IOException: empty roll number

What this code does

  • Inside the stream, readMarksUnchecked turns the checked exception into an unchecked one, which the Function is allowed to throw.
  • readAll catches the UncheckedIOException and rethrows e.getCause(), the original IOException. To its callers, readAll looks like any normal method with throws IOException.

The usual fix has two parts. A small helper method catches the IOException and throws UncheckedIOException, and the stream calls that helper. Then, outside the stream, catch UncheckedIOException and rethrow e.getCause(), so the public method keeps its honest throws IOException.

Next step

Check your understanding

12 quick questions