Lesson 16 of 23

In progress

Course progress

Java

Exceptions and cleanup

Catch what you can handle, propagate what you cannot, and use try-with-resources so files close on every path.

An exception is how Java reports that something went wrong. The design question is not how to catch everything; it is which layer can actually do something about the failure.

What you will learn

  • Tell checked from unchecked exceptions.
  • Write try, catch and finally that do not hide errors.
  • Use try-with-resources for anything that must close.

The hierarchy

  • Throwable is the root.
  • Error is for JVM-level problems; do not catch it.
  • Exception is for application problems.
  • RuntimeException is the unchecked branch of Exception.

Checked exceptions extend Exception but not RuntimeException. The compiler requires them to be caught or declared. Unchecked exceptions extend RuntimeException and signal programming errors: a null, a bad index, an illegal argument.

The rule of thumb: checked for conditions a caller can reasonably recover from (a missing file, a network timeout), unchecked for bugs (a null where a value was required).

Catching

try {
int qty = Integer.parseInt(input);
System.out.println("quantity: " + qty);
} catch (NumberFormatException e) {
System.out.println("not a number: " + input);
}

Catch the most specific type you can handle. catch (Exception e) catches everything, including errors you did not anticipate, and usually ends up logging and continuing in a broken state.

Multiple catches are checked in order, so a subclass must come before its parent:

try {
read(path);
} catch (java.nio.file.NoSuchFileException e) {
System.out.println("missing: " + path);
} catch (java.io.IOException e) {
System.out.println("read failed: " + e.getMessage());
}

finally and try-with-resources

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
static String firstLine(String path) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
return reader.readLine();
}
}

try-with-resources closes the reader on every path, including an early return and an exception. It replaces the older finally block and is less error-prone, because you cannot forget the close or mis-order the null check.

Any class implementing AutoCloseable works, which includes streams, readers, channels and JDBC objects.

finally still has a place for cleanup that is not a resource close:

try {
startJob();
} finally {
stopJob();
}

Do not return from finally: it discards the exception and the original return value, which makes failures disappear.

Declaring and wrapping

static String load(String path) {
try {
return java.nio.file.Files.readString(java.nio.file.Path.of(path));
} catch (java.io.IOException e) {
throw new IllegalStateException("could not load " + path, e);
}
}

Wrapping converts a checked exception into one the caller is not forced to handle. The original is passed as the cause, so the stack trace keeps the detail. Losing the cause — throw new IllegalStateException(e.getMessage()) — discards the most useful part.

throw versus throws: throw raises an exception, throws declares that a method may raise one.

Custom exceptions

public class InsufficientStockException extends RuntimeException {
private final String sku;
public InsufficientStockException(String sku) {
super("no stock for " + sku);
this.sku = sku;
}
public String sku() {
return sku;
}
}

A custom type lets callers catch precisely that failure and carry data with it. Extend RuntimeException for a programming or business rule, and a checked exception when the caller is expected to recover.

Do not create an exception type per method. A handful that map to real recovery paths is enough; the rest can be IllegalArgumentException or IllegalStateException.

Messages that help

A good message says what failed, with what value, and what was expected:

throw new IllegalArgumentException("expected quantity >= 1, got " + qty);

A bad one repeats the exception type: "invalid quantity". The stack trace already says where; the message should say what.

Anti-patterns

  • Swallowing: catch (Exception e) { }. The failure vanishes and the program continues with bad state.
  • Logging and rethrowing: produces duplicate entries and hides the layer that handled it. Either handle or propagate.
  • Catching Throwable: includes OutOfMemoryError, which you cannot recover from.
  • Exceptions for flow control: parsing with exceptions in a tight loop is slow and obscure; check the input first when a check is cheap.
  • printStackTrace: writes to standard error without structure. Use a logger.

Designing the boundary

At the edge of an application — a request handler, a main method — catch, log with context, and return an error the caller can act on. Inside the application, let exceptions propagate to the layer that understands them.

That division keeps every layer from needing to know about every failure, and it means a new failure type is handled in one place rather than five.

Catching an exception, logging it, and returning a default value. The caller cannot tell success from failure, and the missing data surfaces much later in a report.

Write a method that parses a list of strings into integers, skipping invalid entries, and reports how many were skipped. Use a specific catch and a clear message.

Show solution
import java.util.ArrayList; import java.util.List; public class Parse { static List<Integer> parseAll(List<String> inputs, int[] skipped) { List<Integer> numbers = new ArrayList<>(); for (String input : inputs) { try { numbers.add(Integer.parseInt(input.strip())); } catch (NumberFormatException e) { skipped[0]++; System.out.println("skipped: " + input); } } return numbers; } public static void main(String[] args) { int[] skipped = {0}; System.out.println(parseAll(List.of("1", "x", "3", ""), skipped)); System.out.println("skipped count: " + skipped[0]); } }

The catch is specific to the parse failure, which is the only error expected here. Skipping is a decision the caller can see, because the count is reported rather than swallowed, and valid values still come back.

Recap

  • Catch the most specific exception you can handle; let the rest propagate.
  • Try-with-resources closes on every path and replaces most finally blocks.
  • Wrap with the original cause, and write messages that name the value and the rule.

Next, generics: writing code that works for many types while keeping the compiler’s checks.

Should main declare throws Exception?
For a small script it is acceptable. For anything longer, handle it where you can add context.
Is catching RuntimeException bad?
Catching a specific one, such as `NumberFormatException`, is normal. Catching all of them hides bugs.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.