Java exceptions: checked vs unchecked, try-with-resources and error messages
When Java forces you to handle an exception and when it doesn't, how try-with-resources closes files for you, writing your own exceptions, and the mistakes that hide real bugs.
Exceptions are how Java reports that something couldn't be done. Handling them well is the difference between "the app crashed" and "the file was missing; here's what to do".
The hierarchy
Throwable
├── Error (JVM problems: OutOfMemoryError; don't catch)
└── Exception (checked: must be caught or declared)
├── IOException
└── RuntimeException (unchecked)
├── IllegalArgumentException
├── IllegalStateException
└── NullPointerExceptionChecked exceptions describe things outside your control that a caller should plan for: a file that doesn't exist, a network that's down. The compiler forces you to handle or declare them.
Unchecked exceptions usually mean a bug or a broken precondition: a null where none should be, an invalid argument. The compiler doesn't force handling.
Handle or declare
// handle it here
try {
List<String> lines = Files.readAllLines(Path.of("prices.csv"));
} catch (NoSuchFileException e) {
System.out.println("prices.csv not found");
} catch (IOException e) {
System.out.println("Couldn't read prices.csv: " + e.getMessage());
}
// or let the caller decide
List<String> readPrices() throws IOException {
return Files.readAllLines(Path.of("prices.csv"));
}Order matters: catch the more specific exception first (NoSuchFileException extends
IOException).
try-with-resources
Anything that implements AutoCloseable (files, readers, sockets, database connections) can be
opened in the try header and is closed automatically, even if an exception is thrown:
try (BufferedReader in = Files.newBufferedReader(Path.of("loans.csv"))) {
String line;
while ((line = in.readLine()) != null) process(line);
}No finally { in.close(); } needed, and no leaked file handles.
Throwing your own
Validate inputs early, with a message that says what was wrong:
public void lend(String isbn, int days) {
if (days < 1 || days > 28) {
throw new IllegalArgumentException("Loan length must be 1-28 days, got " + days);
}
}A custom exception is worth it when callers need to tell it apart:
public class BookUnavailableException extends Exception {
public BookUnavailableException(String isbn) {
super("Book " + isbn + " is already on loan");
}
}When you wrap an exception, pass the original as the cause so the stack trace survives:
throw new ImportFailedException("Bad row 12", e);.
Mistakes that hide bugs
- Empty catch blocks:
catch (Exception e) {}turns a crash into silent wrong behaviour. - Catching
ExceptionorThrowablewhere you meant one specific exception. - Using exceptions for normal control flow, like ending a loop.
- Losing the cause when rethrowing.
You meet exceptions in Java Fundamentals and design your own in Java Intermediate.
Questions and answers
- What is the difference between checked and unchecked exceptions in Java?
- Checked exceptions (subclasses of Exception but not RuntimeException, like IOException) must be caught or declared with throws. Unchecked exceptions (RuntimeException and its subclasses, like IllegalArgumentException) don't have to be, and usually signal programming errors.
- Is catching Exception a bad idea?
- Usually. It also catches bugs such as NullPointerException that you didn't plan for, often hiding them. Catch the specific exceptions you can actually handle, and let the rest propagate to a top-level handler that logs them.
Practise it
Read next
- Java collections: choosing between List, Set, Map and Deque
ArrayList vs LinkedList, HashMap vs TreeMap, HashSet vs LinkedHashSet, ArrayDeque for stacks and queues: what each costs and which to reach for first.
- Java concurrency basics: threads, ExecutorService and thread-safe code
Why shared mutable state breaks under threads, using ExecutorService and Future instead of raw threads, synchronized, atomic variables, ConcurrentHashMap and CompletableFuture.