What to catch and what to leave alone
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Catching an exception is a decision, not a habit. Catch a problem only where you can do something useful about it, catch the most specific type that fits, and let everything else travel up to code that knows what to do.
Why not to catch Error
An Error such as OutOfMemoryError or StackOverflowError means the JVM itself is in trouble, so code that catches it rarely has a real answer. Memory is still full and the bug that caused the deep recursion is still there.
Example 1 · Catching Error hides a bug
public class HiddenBugDemo { static int instalmentsTotal(int months, int perMonth) { if (months == 0) { return 0; } return perMonth + instalmentsTotal(months - 1, perMonth); }
// Bad: turns a crash into a wrong answer static int totalOrZero(int months, int perMonth) { try { return instalmentsTotal(months, perMonth); } catch (Throwable t) { return 0; } }
// Good: stop the bad input before it can cause the Error static int totalChecked(int months, int perMonth) { if (months < 0) { throw new IllegalArgumentException("months must be 0 or more, got " + months); } return instalmentsTotal(months, perMonth); }
public static void main(String[] args) { System.out.println("6 months: Rs " + totalOrZero(6, 5000)); System.out.println("-3 months: Rs " + totalOrZero(-3, 5000)); try { System.out.println("-3 months: Rs " + totalChecked(-3, 5000)); } catch (IllegalArgumentException e) { System.out.println("Fixed version: " + e.getMessage()); } }}6 months: Rs 30000 -3 months: Rs 0 Fixed version: months must be 0 or more, got -3
What this code does
- With -3,
monthsnever reaches 0, so the recursion runs untilStackOverflowError.catch (Throwable t)hides it and returns Rs 0, a wrong answer with no warning. totalCheckedremoves the cause: it rejects a negative value at once with a clearIllegalArgumentException, so noErrorhappens at all.
Worse, a wide catch hides the bug. catch (Throwable t) or catch (Error e) that returns a default turns a crash into a wrong answer, and wrong answers are much harder to find than crashes. The fix is to remove the cause: validate the input, give the recursion a base case that is always reached, or process data in smaller parts. Leave Error types alone and let the program stop with a clear trace.
Specific catch blocks before general ones
Java tries catch blocks from top to bottom and runs only the first one whose type matches the exception. So a specific type must come before its parent: NumberFormatException before IllegalArgumentException, and both before RuntimeException or Exception.
Example 2 · Specific first: a UPI payment
public class UpiCatchOrderDemo { static final int DAILY_LIMIT = 100000;
static void pay(String amountText, String upiId) { try { int amount = Integer.parseInt(amountText); if (amount <= 0 || amount > DAILY_LIMIT) { throw new IllegalArgumentException("amount must be 1 to " + DAILY_LIMIT); } if (!upiId.contains("@")) { throw new IllegalStateException("UPI ID " + upiId + " is not linked"); } System.out.println("Paid Rs " + amount + " to " + upiId); } catch (NumberFormatException e) { // most specific System.out.println("Enter digits only: " + amountText); } catch (IllegalArgumentException e) { // parent of NumberFormatException System.out.println("Invalid amount: " + e.getMessage()); } catch (RuntimeException e) { // everything else System.out.println("Payment failed: " + e.getMessage()); } }
public static void main(String[] args) { pay("250", "canteen@upi"); pay("2,50", "canteen@upi"); pay("0", "canteen@upi"); pay("500", "canteen"); }}Paid Rs 250 to canteen@upi Enter digits only: 2,50 Invalid amount: amount must be 1 to 100000 Payment failed: UPI ID canteen is not linked
What this code does
"2,50"throwsNumberFormatException. It is also anIllegalArgumentException, but the first matching block wins, so the user gets the more helpful "digits only" message.- The amount 0 throws a plain
IllegalArgumentException, so the first block does not match and the second one runs. TheIllegalStateExceptionmatches only the last block.
Each specific block can give a precise message or a precise fix. A general block at the end catches whatever is left, with a general message.
Multi-catch with a vertical bar
A multi-catch block handles several exception types with one catch, separated by |: catch (NumberFormatException | ArithmeticException e). Use it when the handling is the same for all of them, instead of copying the same block twice.
Example 3 · One block for two unrelated problems
public class MultiCatchDemo { static void average(String subject, String totalText, String countText) { try { int total = Integer.parseInt(totalText); int count = Integer.parseInt(countText); System.out.println(subject + " average: " + (total / count)); } catch (NumberFormatException | ArithmeticException e) { System.out.println(subject + " skipped (" + e.getClass().getSimpleName() + ")"); } }
public static void main(String[] args) { average("Maths", "2460", "30"); average("Physics", "2l00", "30"); average("Chemistry", "0", "0"); }}Maths average: 82 Physics skipped (NumberFormatException) Chemistry skipped (ArithmeticException)
What this code does
"2l00"has a letter l instead of a 1, soparseIntfails. A count of 0 makestotal / countthrowArithmeticException. Both need the same answer, so one block handles both.- The two types are unrelated (neither extends the other), which multi-catch requires.
getClass()still tells you which one actually happened.
Two rules apply. The types must not be parent and child, because the parent alone would already cover the child. And the variable e is automatically final, so you cannot assign a new value to it inside the block.
Compiler error: exception has already been caught
exception X has already been caught is the compiler's message when a catch for a child type comes after a catch for its parent. The child block could never run, so Java treats it as a mistake rather than silently ignoring it.
Example 4 · A child caught after its parent
import java.io.FileNotFoundException;import java.io.IOException;
public class AlreadyCaughtDemo { static String openFeeFile(String name) throws IOException { if (name.isEmpty()) { throw new FileNotFoundException("no file name given"); } return "opened " + name; }
public static void main(String[] args) { try { System.out.println(openFeeFile("fees.csv")); } catch (IOException e) { System.out.println("Could not read the fee file"); } catch (FileNotFoundException e) { System.out.println("Fee file is missing"); } }}AlreadyCaughtDemo.java:17: error: exception FileNotFoundException has already been caught
} catch (FileNotFoundException e) {
^
1 errorWhat this code does
- Every
FileNotFoundExceptionis anIOException, so the first block always takes it. The second block is dead code, and the compiler reports it. - Fix: swap the two blocks, so
FileNotFoundExceptioncomes first andIOExceptioncatches the other input problems.
exception FileNotFoundException has already been caught: movecatch (FileNotFoundException e)abovecatch (IOException e).Alternatives in a multi-catch statement cannot be related by subclassing: keep only the parent in the|list.multi-catch parameter e may not be assigned: use a new local variable instead of changinge.
The fix is to move the specific block above the general one, or to delete it if both blocks do the same thing.
The danger of an empty catch block
An empty catch block, such as catch (Exception e) { }, swallows the exception: the problem happens, but nobody ever hears about it. The program goes on with missing or wrong data, and the bug shows up much later, far from its cause.
Example 5 · An empty catch versus a reported one
import java.util.List;
public class EmptyCatchDemo { static int totalSilent(List<String> rows) { int total = 0; for (String row : rows) { try { total += Integer.parseInt(row.split(",")[1].trim()); } catch (RuntimeException e) { // nothing here: the problem disappears } } return total; }
static int totalWithReport(List<String> rows) { int total = 0; int skipped = 0; for (String row : rows) { try { total += Integer.parseInt(row.split(",")[1].trim()); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { skipped++; System.out.println("Skipped row \"" + row + "\": " + e.getClass().getSimpleName()); } } System.out.println("Rows skipped: " + skipped); return total; }
public static void main(String[] args) { List<String> attendance = List.of("CS101, 22", "CS102, 2O", "CS103", "CS104, 25"); System.out.println("Silent total days: " + totalSilent(attendance)); System.out.println("Reported total days: " + totalWithReport(attendance)); }}Silent total days: 47 Skipped row "CS102, 2O": NumberFormatException Skipped row "CS103": ArrayIndexOutOfBoundsException Rows skipped: 2 Reported total days: 47
What this code does
- Both methods give 47, but only the second one says that two students are missing. With the silent version, nobody would ever know the total is incomplete.
- The reported version also catches only the two types it expects. A real bug such as a
NullPointerExceptionwould still stop the program instead of being swallowed.
If you catch, do something visible: print or log a message, count the skipped item, use a clearly named default, or throw a better exception. If you have nothing to do, do not catch at all.
Find the bug
Spot the dangerous catch
Select the line that is wrong.
This should tell the user when the marks are not a number.
Round 1 of 3Next step
Check your understanding
12 quick questions