Skip to lesson

Where to catch: anti-patterns

Most error handling bugs are not missing try blocks but badly placed ones. A catch block belongs where the code can actually do something: retry, fall back, translate or tell the user. Everywhere else it hides problems or repeats them.

Swallowed exceptions

A swallowed exception is one that is caught and then ignored, for example in an empty catch block, so the program carries on as if nothing went wrong.

A swallowed exception is one that is caught and then ignored: an empty catch block, or one that holds only a comment such as // TODO. The program carries on as if nothing happened.

Example 1 · A swallowed exception, and the fix

SwallowDemo.javaJava
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class SwallowDemo {    static void saveSettingsBad(Path file, String text) {        try {            Files.writeString(file, text);        } catch (IOException e) {            // TODO handle later          <- the error disappears here        }    }
    static void saveSettings(Path file, String text) throws IOException {        Files.writeString(file, text);                 // let the caller decide    }
    public static void main(String[] args) throws IOException {        Path folder = Files.createTempDirectory("app");        Path file = folder.resolve("config").resolve("settings.txt");  // "config" does not exist
        saveSettingsBad(file, "theme=dark");        System.out.println("Settings saved");        System.out.println("File really exists: " + Files.exists(file));
        try {            saveSettings(file, "theme=dark");            System.out.println("Settings saved");        } catch (IOException e) {            System.out.println("Could not save settings: " + e.getClass().getSimpleName());        }
        Files.delete(folder);    }}
Output
Settings saved
File really exists: false
Could not save settings: NoSuchFileException

What this code does

  • Writing into a folder that does not exist throws NoSuchFileException. saveSettingsBad swallows it, so the program happily prints "Settings saved" even though no file was written.
  • saveSettings does not catch at all; main, which can talk to the user, catches the IOException and reports it honestly.

That is the worst outcome. The user is told "Settings saved" when nothing was saved, the log is empty, and the bug shows up days later as missing data with no trace of the cause. If a method cannot do anything useful with an exception, it should not catch it at all. Let it travel up to code that can act.

Log and rethrow: the same error logged twice

Log and rethrow means a catch block that writes the exception to the log and then throws it (or a wrapper) again. When every layer does this, one failure appears in the log two, three or four times, each with its own stack trace.

Example 2 · Log and rethrow at every layer versus log once

LogAndRethrowDemo.javaJava
import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;
class StorageException extends RuntimeException {    StorageException(String message, Throwable cause) {        super(message, cause);    }}
public class LogAndRethrowDemo {    static {   // only for this page: short log lines on System.out (no date, no stack trace)        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n");    }
    private static final Logger LOG = Logger.getLogger(LogAndRethrowDemo.class.getName());
    static String readFile(String name) throws IOException {        throw new IOException("disk read error");    }
    // Anti-pattern: every layer logs, then throws again    static String loadBad(String cls) {        try {            return readFile(cls + ".csv");        } catch (IOException e) {            LOG.log(Level.SEVERE, "storage: could not read " + cls, e);            throw new StorageException("Could not load marks for class " + cls, e);        }    }
    static String reportBad(String cls) {        try {            return loadBad(cls);        } catch (StorageException e) {            LOG.log(Level.SEVERE, "service: report failed for " + cls, e);            throw e;        }    }
    // Better: lower layers only translate; the top logs once    static String load(String cls) {        try {            return readFile(cls + ".csv");        } catch (IOException e) {            throw new StorageException("Could not load marks for class " + cls, e);        }    }
    static String report(String cls) {        return load(cls);    }
    public static void main(String[] args) {        System.out.println("-- log and rethrow --");        try {            reportBad("10B");        } catch (StorageException e) {            LOG.log(Level.SEVERE, "top: request failed", e);        }
        System.out.println("-- log once at the top --");        try {            report("10B");        } catch (StorageException e) {            LOG.log(Level.SEVERE, "Request failed: " + e.getMessage(), e);        }    }}
Output
-- log and rethrow --
SEVERE: storage: could not read 10B
SEVERE: service: report failed for 10B
SEVERE: top: request failed
-- log once at the top --
SEVERE: Request failed: Could not load marks for class 10B

What this code does

  • One disk error produced three SEVERE entries. In a real log each would also carry a full stack trace, so one problem looks like three.
  • In the better version load translates and keeps the cause without logging, report does not catch at all, and main writes one entry that still contains the whole cause chain.

The log becomes hard to read, alert counts are wrong, and people waste time looking for three problems when there was one. The rule: in each catch block, either handle the exception (and log it once) or pass it on (translate it, keep the cause, do not log). The code that finally handles it writes the one log entry.

Predict the output

What do these anti-patterns do?

Read each program and pick what it prints.

Round 1 of 3

Two layers each log the same failure.

public class LogCount {
static int logged = 0;
static void load() {
throw new IllegalStateException("file missing");
}
static void service() {
try {
load();
} catch (IllegalStateException e) {
logged++;
throw e;
}
}
public static void main(String[] args) {
try {
service();
} catch (IllegalStateException e) {
logged++;
}
System.out.println("Logged " + logged + " time(s)");
}
}

catch Exception everywhere

catch (Exception e) catches every checked exception and every RuntimeException, including bugs such as NullPointerException and ArrayIndexOutOfBoundsException. A block meant for "the file could not be read" then also hides programming errors behind the same message.

Example 3 · catch Exception hides a bug

CatchAllDemo.javaJava
import java.io.IOException;import java.nio.file.NoSuchFileException;
public class CatchAllDemo {    static String readMarks(String cls) throws IOException {        String key = cls.toUpperCase();        // NullPointerException if cls is null: a bug        if (!key.equals("10A")) {            throw new NoSuchFileException(key + ".csv");        }        return "10A: 78, 91";    }
    static String broad(String cls) {        try {            return readMarks(cls);        } catch (Exception e) {                // catches bugs too            return "Could not read the marks file";        }    }
    static String narrow(String cls) {        try {            return readMarks(cls);        } catch (IOException e) {              // only what this code can handle            return "Could not read the marks file for " + cls;        }    }
    public static void main(String[] args) {        String[] classes = {"10A", "10Z", null};
        System.out.println("Broad catch:");        for (String cls : classes) {            System.out.println("  " + cls + " -> " + broad(cls));        }
        System.out.println("Narrow catch:");        for (String cls : classes) {            try {                System.out.println("  " + cls + " -> " + narrow(cls));            } catch (NullPointerException e) {                System.out.println("  " + cls + " -> bug surfaces: " + e.getClass().getSimpleName());            }        }    }}
Output
Broad catch:
  10A -> 10A: 78, 91
  10Z -> Could not read the marks file
  null -> Could not read the marks file
Narrow catch:
  10A -> 10A: 78, 91
  10Z -> Could not read the marks file for 10Z
  null -> bug surfaces: NullPointerException

What this code does

  • With catch (Exception e), the null class (a bug in the caller) gets the same message as a missing file, so nobody will ever look for the bug.
  • With catch (IOException e), the missing file is handled and the NullPointerException passes through. main catches it here only to continue the demo; in a real app it reaches the top-level handler and gets logged as a bug.

Catch the specific types the code can handle: IOException, NumberFormatException, your own StorageException. Let everything else go up. The one good place for a broad catch is the top-level handler, which logs it as unexpected.

Find the bug

Find the error-handling bug

Each snippet handles an IOException badly. Tap the wrong line, then check the fix.

Saving the settings file.

Round 1 of 4

One top-level handler in main

A top-level handler is the one place, usually in main (or around each request in a server), that catches whatever nobody else handled. It is the safety net that turns a crash into a calm message, a log entry and an exit code.

A chain of four calls: main calls report, report calls load, load calls Files.readAllLines. Files.readAllLines, at the bottom, throws IOException. The exception travels back up through load and report, which have no try block, to main at the top, where one catch logs it once and shows a message.

Example 4 · One top-level handler with exit codes

TopLevelDemo.javaJava
import java.util.logging.Level;import java.util.logging.Logger;
class AppException extends RuntimeException {    AppException(String userMessage) {        super(userMessage);    }}
public class TopLevelDemo {    static {   // only for this page: short log lines on System.out (no date, no stack trace)        System.setErr(System.out);        System.setProperty("java.util.logging.SimpleFormatter.format", "%4$s: %5$s%n");    }
    private static final Logger LOG = Logger.getLogger(TopLevelDemo.class.getName());
    static void run(String command) {        switch (command) {            case "report" -> System.out.println("Report for 10A: average 78");            case "import" -> throw new AppException("The file marks.csv has 2 bad rows. Fix them and import again.");            default -> System.out.println(command.substring(10));   // a bug: wrong index        }    }
    // The real main would be: System.exit(handle(args[0]));    static int handle(String command) {        try {            run(command);            return 0;        } catch (AppException e) {            System.out.println("Error: " + e.getMessage());            return 1;        } catch (RuntimeException e) {            LOG.log(Level.SEVERE, "Unexpected error in command " + command, e);            System.out.println("Unexpected error. Details are in the log.");            return 2;        }    }
    public static void main(String[] args) {        for (String command : new String[]{"report", "import", "export"}) {            System.out.println("> " + command);            System.out.println("exit code " + handle(command));        }    }}
Output
> report
Report for 10A: average 78
exit code 0
> import
Error: The file marks.csv has 2 bad rows. Fix them and import again.
exit code 1
> export
SEVERE: Unexpected error in command export
Unexpected error. Details are in the log.
exit code 2

What this code does

  • run has no try blocks. Every failure reaches handle, the single safety net.
  • An AppException carries a message written for users, so it is shown as-is. Anything else (here a StringIndexOutOfBoundsException from the bug) is logged as SEVERE with its stack trace, and the user gets a general sentence and a different exit code.

It typically has two catch blocks: one for the app's own exceptions (show the message, which was written for users), and one for everything else (log it as SEVERE with the stack trace, show a general "unexpected error" sentence). With this net in place, the code below can stay free of try blocks except where it can really act.

Catch where you can act: retry, use a default, translate to the layer's own exception, or tell the user. Anywhere else, let it go up.

Uncaught exception handler for threads

A thread runs code at the same time as main. If an exception escapes a thread's run method, the thread dies; by default Java prints Exception in thread "name" and a stack trace to System.err, and the rest of the program never hears about it.

Example 5 · Uncaught exception handlers for threads

ThreadHandlerDemo.javaJava
public class ThreadHandlerDemo {    public static void main(String[] args) throws InterruptedException {        Thread.setDefaultUncaughtExceptionHandler((t, e) ->                System.out.println("[default handler] " + t.getName() + " died: " + e));
        Thread report = new Thread(() -> {            System.out.println("report-1: building report");            throw new IllegalStateException("marks file is empty");        }, "report-1");        report.setUncaughtExceptionHandler((t, e) ->                System.out.println("[report handler] " + t.getName() + " failed: " + e.getMessage()));
        Thread backup = new Thread(() -> {            throw new IllegalArgumentException("bad backup folder");        }, "backup-1");
        report.start();        report.join();          // wait for the thread to finish        backup.start();        backup.join();        System.out.println("main: still running, both workers finished");    }}
Output
report-1: building report
[report handler] report-1 failed: marks file is empty
[default handler] backup-1 died: java.lang.IllegalArgumentException: bad backup folder
main: still running, both workers finished

What this code does

  • report-1 has its own handler, so its exception goes there. backup-1 has none, so the default handler set with Thread.setDefaultUncaughtExceptionHandler receives it. A real program would log both with LOG.log(Level.SEVERE, ..., e).
  • The handler runs in the dying thread, before join() returns, so the order of lines is fixed. Each failed thread stops, but main keeps running.

An uncaught exception handler is the top-level handler for threads. thread.setUncaughtExceptionHandler((t, e) -> ...) sets one for a single thread, and Thread.setDefaultUncaughtExceptionHandler(...) sets one for every thread without its own. Use it to log the failure properly.

Tasks run with an ExecutorService through submit keep their exception inside the returned Future; it appears only when you call future.get(), not in the handler.

Next step

Check your understanding

12 quick questions