Sub topic 17
Exception Handling Best Practices
You now know how to throw, catch, wrap, and clean up after exceptions. This chapter collects the habits that experienced Java developers follow. A best practice is a way of working that most programmers agree leads to fewer bugs and clearer code.
Catch Specific Types
Catch the exact exception you expect, such as NumberFormatException or IOException. Avoid catch (Exception e) unless you really mean "anything at all." A broad catch can hide bugs you never planned for, such as a NullPointerException.
Never catch Throwable or Error. An Error like OutOfMemoryError means the program is in serious trouble, and your code usually cannot fix it.
Never Swallow an Exception
To swallow an exception means to catch it and do nothing. The failure vanishes, and nobody learns that something went wrong.
public class SwallowDemo {
public static void main(String[] args) {
int n = 0;
try {
n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
// BAD: empty catch block hides the problem
}
System.out.println("n = " + n); // prints 0, and we never learn why
}
}At a minimum, log the exception or tell the user. If you can't handle it, let it propagate or rethrow it.
Wrap, and Keep the Cause
When you turn a low-level exception into a higher-level one, pass the original as the cause. The stack trace then shows both, so you can find where the problem really started.
Use try-with-resources for Cleanup
Any object that implements AutoCloseable belongs in a try-with-resources statement. It is shorter than a manual finally block, and it never loses an exception thrown by close().
Check Arguments Early and Write Clear Messages
Throw IllegalArgumentException as soon as you see bad input. This is called failing fast. Put the bad value in the message so the reader knows what went wrong.
Putting It Together
This program follows every rule above.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConfigLoader {
static String loadSetting(Path path) {
if (path == null) {
throw new IllegalArgumentException("path must not be null");
}
try (BufferedReader reader = Files.newBufferedReader(path)) {
return reader.readLine();
} catch (IOException e) {
throw new UncheckedIOException("Could not read config file " + path, e);
}
}
public static void main(String[] args) {
try {
System.out.println(loadSetting(Path.of("missing.txt")));
} catch (UncheckedIOException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
}
}
}The method checks its argument first. It closes the file automatically, catches only IOException, and wraps that exception with a clear message while keeping the original cause.
Quick Reference
| Do | Avoid |
|---|---|
| Catch specific types | `catch (Exception e)` everywhere |
| Log or rethrow | Empty catch blocks |
| Pass the cause when wrapping | Throwing away the original exception |
| Use try-with-resources | Manual `close()` in `finally` |
| Use clear messages with values | Messages like "error" |
| Use `if` checks for normal cases | Exceptions for ordinary control flow |
Exercise
A teammate writes catch (IOException e) { throw new RuntimeException("load failed"); }. Which best practice does this break, and how do you fix it?
Show answer
It throws away the original exception, so the stack trace no longer shows the real cause. Pass the caught exception as the cause: throw new RuntimeException("load failed", e);.
Exercise
Why is catch (Exception e) {} worse than having no catch block at all?
Show answer
It catches every kind of exception, including bugs you didn't expect, and then hides them. With no catch block, the exception would propagate and print a stack trace that shows the problem.