Rethrow and wrap checked exceptions
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); } } }}receipt sent to CS101 [uploadFee] failed for EE205: mail server rejected the message main: please retry later for EE205
What this code does
uploadFeeadds the roll number to the log, whichsendReceipt's message does not have, and thenthrow e;passes the very same exception on.- Because the exception still leaves
uploadFee, the method keepsthrows IOException, andmainmakes 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.
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
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()); } } }}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, butallotRoomdeclares onlyIOException, InterruptedException. The compiler sees that thetrycan throw only those two checked types. - So
maincan still catch the two types separately. Without precise rethrow,allotRoomwould needthrows Exception, and every caller would have to catch plainException.
Example 3 · Assigning to the catch variable breaks it
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"); }}ReassignRethrowDemo.java:15: error: unreported exception Exception; must be caught or declared to be thrown
throw e;
^
1 errorWhat this code does
- The line
e = new IOException(...)makeseno longer effectively final, sothrow e;now counts as throwing plainException, which the method does not declare. - Fix: leave
ealone and throw a new variable instead, for examplethrow new IOException("hostel office: " + e.getMessage(), e);inside theif.
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
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()); } }}sorted: [CS7, CS45, CS1012] cannot sort photos <- photo missing for CS9X
What this code does
comparingLongneeds a function that cannot throw checked exceptions, sophotoSizecannot be used directly.photoSizeUncheckedwraps theIOExceptionin anUncheckedIOException.- Outside the sort,
e.getCause()gives the originalIOException, 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
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); }}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 errorWhat this code does
maptakes aFunction, whoseapplymethod declares no checked exceptions, so the lambda body may not throwIOException.mainalready saysthrows 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
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()); } }}[65, 63] main caught IOException: empty roll number
What this code does
- Inside the stream,
readMarksUncheckedturns the checked exception into an unchecked one, which theFunctionis allowed to throw. readAllcatches theUncheckedIOExceptionand rethrowse.getCause(), the originalIOException. To its callers,readAlllooks like any normal method withthrows 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