public static String readFirstLine(Path path) throws IOException {
FileInputStream fis = new FileInputStream(path.toFile());
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
reader.close();
return line;
}
This compiles and runs. It also leaks resources when readLine() throws an exception, because reader.close() never executes. If close() itself throws, it replaces whatever exception readLine() raised, losing the original failure reason. And it closes only reader, leaving isr and fis open.
Three separate problems, one common pattern. Java solved them together.
try-with-resources
A resource in Java is any object whose class implements AutoCloseable. The close() method is called automatically when the block exits.
try (FileInputStream fis = new FileInputStream(path.toFile());
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(isr)) {
return reader.readLine();
}
The compiler generates a finally block that calls close() on each resource, in reverse order of declaration. reader closes first, then isr, then fis. Reverse order matters: reader wraps isr, which wraps fis, so closing the outermost first flushes any internal buffers before the underlying streams close.
What happens when both the try block and close() throw? The close() exception is suppressed : it is attached to the original exception but does not replace it. You can inspect suppressed exceptions with e.getSuppressed(). Without try-with-resources, a close() exception silently discards the original failure. That makes diagnosis impossible: the stack trace points to close(), not to the actual problem.
Use try-with-resources for every Closeable or AutoCloseable: files, streams, database connections, PreparedStatement, JDBC result sets, HTTP clients with explicit close methods. If the type implements AutoCloseable, do not manage its lifetime in a finally block.
You can also implement AutoCloseable in your own classes:
public class MeasuredScope implements AutoCloseable {
private final String name;
private final long startNanos;
public MeasuredScope(String name) {
this.name = name;
this.startNanos = System.nanoTime();
}
@Override
public void close() {
long elapsed = System.nanoTime() - startNanos;
System.out.printf("%s: %d ms%n", name, elapsed / 1_000_000);
}
}
try (MeasuredScope scope = new MeasuredScope("parse")) {
parseDocument(input);
}
close() does not need to release a system resource. It runs at the end of the block regardless, so it works for anything where "execute this cleanup code" is useful.
Exception chaining
When you catch an exception and throw a different one, preserve the original as the cause:
} catch (IOException e) {
throw new DataAccessException("Failed to load configuration", e);
}
The Throwable cause argument is the second parameter in the standard exception constructors. The cause is accessible via getCause() and appears in the stack trace as "Caused by:":
Exception in thread "main" com.example.DataAccessException: Failed to load configuration
at com.example.ConfigLoader.load(ConfigLoader.java:31)
at com.example.Main.main(Main.java:12)
Caused by: java.io.FileNotFoundException: /etc/app/config.json (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
...
Without the cause, your DataAccessException appears to have no origin. Someone diagnosing a production failure sees only "Failed to load configuration" and has to guess what actually went wrong. The "Caused by:" chain shows the full picture.
The cause is useful in both directions: catching a low-level checked exception and re-throwing as an unchecked exception (wrapping), and catching an unchecked exception to add domain context (enriching). In both cases, pass the original.
Do not catch an exception, log it, and then re-throw it. That produces a duplicate log entry for the same failure. Either log it and swallow it (acceptable when you have genuinely handled it), or re-throw it and let the caller log it. Doing both means every handler in the call stack logs the same event.
Custom exception types
When you need a checked exception for a recoverable condition in your domain, create a subclass of Exception:
public class InsufficientFundsException extends Exception {
private final int requested;
private final int available;
public InsufficientFundsException(int requested, int available) {
super("Requested " + requested + " but only " + available + " available");
this.requested = requested;
this.available = available;
}
public int getRequested() { return requested; }
public int getAvailable() { return available; }
}
Adding fields for the domain values means the caller can inspect the exception programmatically. InsufficientFundsException.getRequested() returns a number your code can compare against a limit or display to a user. A generic Exception("not enough funds") forces the caller to parse the message string, which breaks the moment the message wording changes.
For unchecked exceptions that signal programming errors, extend RuntimeException:
public class InvalidAccountStateException extends RuntimeException {
public InvalidAccountStateException(String message) {
super(message);
}
public InvalidAccountStateException(String message, Throwable cause) {
super(message, cause);
}
}
Provide both constructors. Code that catches a lower-level exception and wants to re-throw it as InvalidAccountStateException needs the cause form. Code that detects the bad state directly uses the message-only form.
The checked versus unchecked decision
When designing an API method that can fail, the question is: can a reasonable caller recover from this failure?
If yes, use a checked exception. The compiler forces every caller to handle it or declare it. This is the right choice when the failure is a normal part of the interaction: InsufficientFundsException, AccountLockedException, ParseException. The caller chose to call withdraw() and must be prepared for the account to be short.
If no, use an unchecked exception. The failure is a programming error on the caller's side: a null argument where null is not allowed, an index out of range, an object that was used after it was closed. Requiring every caller to catch these exceptions creates noise without benefit. The right response to a programming error is to fix the calling code, not to surround every call with a try-catch.
A related test: if a checked exception type propagates through 10 methods and only one caller can meaningfully handle it, every intermediate method has to declare throws YourException. The declaration adds noise and couples those methods to your exception type. When you find yourself wrapping a checked exception in RuntimeException just to escape a throws chain, that is a signal the exception should have been unchecked in the first place.
Common mistakes
Catching Exception or Throwable to suppress the error. This hides bugs and makes failures silent. If you catch Throwable, you catch Error too, including OutOfMemoryError and StackOverflowError. That almost never ends well. Catch the specific type you know how to handle.
Empty catch blocks. A completely empty catch block eats the exception and leaves no trace. If you genuinely intend to swallow an exception, write a comment explaining why:
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore interrupt status
}
Swallowing while pretending to log. This pattern destroys the cause chain:
} catch (IOException e) {
logger.error("Failed"); // no exception passed to logger
throw new RuntimeException("Failed"); // no cause
}
Both the log entry and the re-thrown exception lose the original IOException. Pass the exception to the logger: logger.error("Failed", e). Pass it to the constructor: new RuntimeException("Failed", e).
Using exceptions for control flow. Throwing an exception to signal "not found" in a search is expensive: the JVM captures the full stack trace on construction. Use Optional<T> or return null with a documented contract for "not found" cases. Reserve exceptions for genuinely exceptional conditions.
Prediction exercise
public static String findUser(Map<String, String> users, String id) {
try {
String name = users.get(id);
return name.toUpperCase();
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
return "unknown";
}
}
Call this with a map that contains the key "42" mapping to null. What does e.getMessage() print? What does the method return? Then: why is catching Exception here a problem even though it "works" in this case?
The exception mechanism, the common types, and the design patterns together cover how Java programs signal and recover from failure. The next area in the curriculum is generics: how Java preserves type information across reusable components, and what erasure takes away.

Top comments (0)