Skip to content

Module 8 · Exceptions and File Handling — topic 2 of 3

Custom Exceptions and try-with-resources

Designing your own exception classes, checked versus unchecked custom exceptions, chaining causes, AutoCloseable and try-with-resources, and suppressed exceptions.

Beginner 15 min read·Lesson 28 of 39 in Java Programming

Learning objectives

  • Create checked and unchecked custom exceptions
  • Wrap low-level exceptions while preserving the cause
  • Use try-with-resources to close resources reliably

Definition

A custom exception is a class that extends Exception (checked) or RuntimeException (unchecked) to represent a domain-specific error. try-with-resources automatically closes objects implementing AutoCloseable when the block ends.

Introduction

IllegalArgumentException("insufficient funds") works, but callers can't distinguish it from any other bad argument. An InsufficientFundsException that carries the balance and the requested amount lets them react precisely. And because resources such as files and database connections must always be closed, Java provides try-with-resources to do it for you.

Why it matters

Meaningful exception types make APIs self-documenting and error handling precise.

Forgetting to close files and connections leaks resources; try-with-resources makes that impossible.

Detailed explanation

Defining one. Extend Exception for a checked exception (callers must handle it) or RuntimeException for an unchecked one. Provide constructors that take a message and, ideally, a cause: super(message, cause).

Choosing checked or unchecked. Use checked exceptions for recoverable conditions the caller should consider (a payment is declined, a file is missing). Use unchecked exceptions for programming errors and invalid arguments. Many modern libraries prefer unchecked exceptions to keep code concise.

Extra data. Add fields (the requested amount, the invalid value) and getters, so handlers can act on the details rather than parsing messages.

Chaining. When translating a low-level exception into a higher-level one, pass the original as the cause: throw new ReportException("cannot load report", e);. The stack trace then shows both, and getCause() retrieves the original.

try-with-resources (Java 7). try (var r = new Resource()) { ... } calls r.close() automatically when the block ends, whether normally or by an exception. Several resources are closed in reverse order of opening. Any class implementing AutoCloseable (or Closeable) works.

Suppressed exceptions. If the body throws and close() also throws, the body's exception is the one propagated and the close exception is attached to it as *suppressed* — available through getSuppressed().

Syntax

Java
class InsufficientFundsException extends Exception { // checked
private final long shortfall;
InsufficientFundsException(long shortfall) {
super("short by " + shortfall);
this.shortfall = shortfall;
}
long shortfall() { return shortfall; }
}
try (BufferedReader in = Files.newBufferedReader(path)) { // closed automatically
...
} catch (IOException e) {
throw new UncheckedIOException("cannot read " + path, e); // chain the cause
}
  • Name exception classes with an Exception suffix.
  • Always keep the original exception as the cause when wrapping.
  • Resources declared in try(...) are effectively final.

Code examples

A checked custom exception with data

Java
public class Main {
public static void main(String[] args) {
Wallet w = new Wallet(500);
long[] spends = {200, 450};
for (long amount : spends) {
try {
w.spend(amount);
System.out.println("spent " + amount + ", left " + w.balance());
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + " -> top up at least " + e.shortfall());
}
}
}
}
class InsufficientFundsException extends Exception {
private final long shortfall;
InsufficientFundsException(long requested, long available) {
super("cannot spend " + requested + ", only " + available + " available");
this.shortfall = requested - available;
}
long shortfall() { return shortfall; }
}
class Wallet {
private long balance;
Wallet(long balance) { this.balance = balance; }
long balance() { return balance; }
void spend(long amount) throws InsufficientFundsException {
if (amount > balance) throw new InsufficientFundsException(amount, balance);
balance -= amount;
}
}
Output
spent 200, left 300
cannot spend 450, only 300 available -> top up at least 150

try-with-resources closes in reverse order

Java
public class Main {
public static void main(String[] args) {
try (Resource db = new Resource("database"); Resource log = new Resource("log file")) {
System.out.println("working with " + db.name + " and " + log.name);
}
System.out.println("done");
}
}
class Resource implements AutoCloseable {
final String name;
Resource(String name) {
this.name = name;
System.out.println("open " + name);
}
@Override public void close() { System.out.println("close " + name); }
}
Output
open database
open log file
working with database and log file
close log file
close database
done

More examples

Chaining causes and suppressed exceptions

Java
public class Main {
public static void main(String[] args) {
try {
new ReportService().load("sales-2026");
} catch (ReportException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("Caused by: " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage());
}
try (FlakyConnection c = new FlakyConnection()) {
c.query();
} catch (Exception e) {
System.out.println("Primary: " + e.getMessage());
for (Throwable s : e.getSuppressed()) System.out.println("Suppressed: " + s.getMessage());
}
}
}
class ReportException extends RuntimeException { // unchecked
ReportException(String message, Throwable cause) { super(message, cause); }
}
class ReportService {
void load(String id) {
try {
parseRow("2026-01,North,abc");
} catch (NumberFormatException e) {
throw new ReportException("could not load report " + id, e); // keep the cause
}
}
private int parseRow(String row) {
return Integer.parseInt(row.split(",")[2]);
}
}
class FlakyConnection implements AutoCloseable {
void query() { throw new IllegalStateException("query failed"); }
@Override public void close() throws Exception { throw new Exception("close failed too"); }
}
Output
Error: could not load report sales-2026
Caused by: NumberFormatException: For input string: "abc"
Primary: query failed
Suppressed: close failed too

Step-by-step explanation

  • parseRow fails with a low-level NumberFormatException for the text "abc".
  • load catches it and throws a domain-level ReportException, passing the original as the cause.
  • The handler in main reports the high-level message and inspects getCause() for details.
  • In the second try, query() throws, and then the automatic close() throws too.
  • Java propagates the original exception ("query failed") and attaches the close failure as a suppressed exception instead of losing either one.

Expected output

Running “Chaining causes and suppressed exceptions” prints exactly:

TextOutput
Error: could not load report sales-2026
Caused by: NumberFormatException: For input string: "abc"
Primary: query failed
Suppressed: close failed too

Practical applications

  • Domain errors such as OrderNotFoundException or PaymentDeclinedException in business services
  • Wrapping SQLException or IOException in application-level exceptions
  • Closing files, sockets, database connections and locks with try-with-resources

Best practices

  • Create custom exceptions only when callers need to distinguish them.
  • Always chain the cause when wrapping exceptions.
  • Use try-with-resources for anything that implements AutoCloseable.

Common mistakes

Losing the original cause

Avoid

catch (SQLException e) { throw new DataException("query failed"); }

Prefer

catch (SQLException e) { throw new DataException("query failed", e); }

Without the cause, the stack trace no longer shows what actually went wrong in the database.

Closing resources manually

Avoid

Reader r = open();
process(r);
r.close(); // skipped if process throws

Prefer

try (Reader r = open()) {
process(r);
}

If process throws, the manual close never runs; try-with-resources always closes.

Important notes

  • java.io.UncheckedIOException is a ready-made unchecked wrapper for IOException.
  • Since Java 9, an existing effectively-final variable can be used directly: try (reader) { ... }.

Key takeaways

  • Extend Exception for checked and RuntimeException for unchecked custom exceptions.
  • Pass the original exception as the cause when translating it.
  • try-with-resources closes resources automatically, in reverse order, and records suppressed exceptions.

Try it yourself

  1. 1
    Create an InvalidGradeException and use it in a method that converts marks to grades.
  2. 2
    Write a Timer class implementing AutoCloseable that prints how long its block took.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerTo create a checked custom exception, which class do you extend?
  • BeginnerWhat is printed?
  • ModerateWhat is printed?
Practise this topic