Built-in exceptions such as IllegalArgumentException say that something went wrong, but not what it means for your program. A banking app wants to say “insufficient balance”, with the missing amount attached. Custom exceptions let you name your own errors and carry useful data. This lesson also covers try-with-resources, the safe way to make sure files, connections and other resources are always closed.
In this lesson you will learn
- Writing checked and unchecked custom exceptions
- Adding fields and messages to an exception
- Wrapping exceptions while keeping the original cause
- Try-with-resources and
AutoCloseable - Multi-catch and the order of
catchblocks
You should know exception handling basics and inheritance.
Custom Exceptions
public class Main {
// A checked custom exception: callers must handle or declare it
static class InsufficientBalanceException extends Exception {
private final double shortBy;
InsufficientBalanceException(double shortBy) {
super(String.format("Not enough balance: short by %.2f taka", shortBy));
this.shortBy = shortBy;
}
double getShortBy() { return shortBy; }
}
// An unchecked custom exception for programming errors
static class InvalidAmountException extends RuntimeException {
InvalidAmountException(double amount) {
super("Amount must be positive, got " + amount);
}
}
static double balance = 500;
static void withdraw(double amount) throws InsufficientBalanceException {
if (amount <= 0) throw new InvalidAmountException(amount);
if (amount > balance) throw new InsufficientBalanceException(amount - balance);
balance -= amount;
System.out.println("Withdrew " + amount + ", balance now " + balance);
}
public static void main(String[] args) {
double[] requests = {200, 450, -50};
for (double r : requests) {
try {
withdraw(r);
} catch (InsufficientBalanceException e) {
System.out.println("Refused: " + e.getMessage());
System.out.println(" (needs " + e.getShortBy() + " more)");
} catch (InvalidAmountException e) {
System.out.println("Bug in caller: " + e.getMessage());
} finally {
System.out.println(" finished request of " + r);
}
}
// Wrapping a low-level exception while keeping the cause
try {
try {
Integer.parseInt("12a");
} catch (NumberFormatException e) {
throw new IllegalStateException("Could not read amount from file", e);
}
} catch (IllegalStateException e) {
System.out.println(e.getMessage() + " <- caused by " + e.getCause().getClass().getSimpleName());
}
}
}
Output
Withdrew 200.0, balance now 300.0
finished request of 200.0
Refused: Not enough balance: short by 150.00 taka
(needs 150.0 more)
finished request of 450.0
Bug in caller: Amount must be positive, got -50.0
finished request of -50.0
Could not read amount from file <- caused by NumberFormatException
- Extend
Exceptionfor a checked exception. The compiler forces callers to catch it or declarethrows. Use it for problems a caller can reasonably handle, such as a refused withdrawal. - Extend
RuntimeExceptionfor an unchecked exception. Use it for programming mistakes, such as a negative amount, which should be fixed rather than caught everywhere. - Pass a clear message to
super(…), and add fields likeshortByso the handler can act on the details. finallyruns whether the request succeeded or failed.- When converting one exception into another, pass the original as the cause:
new IllegalStateException(msg, e). The stack trace then shows both, which makes debugging much easier.
Try-With-Resources
public class Main {
// Any class that implements AutoCloseable works with try-with-resources
static class Connection implements AutoCloseable {
private final String name;
Connection(String name) {
this.name = name;
System.out.println("open " + name);
}
void send(String msg) {
if (msg.isEmpty()) throw new IllegalArgumentException("empty message");
System.out.println("send " + name + ": " + msg);
}
@Override
public void close() {
System.out.println("close " + name);
}
}
public static void main(String[] args) {
// Resources are closed automatically, in reverse order
try (Connection db = new Connection("database");
Connection log = new Connection("logfile")) {
db.send("SELECT 1");
log.send("query sent");
}
System.out.println("---");
// Even when an exception is thrown, close() still runs first
try (Connection c = new Connection("printer")) {
c.send("");
} catch (IllegalArgumentException e) {
System.out.println("caught: " + e.getMessage());
}
System.out.println("---");
// Multi-catch: one block for several unrelated exceptions
String[] inputs = {"10", "abc", null};
for (String in : inputs) {
try {
System.out.println("length " + in.length() + ", value " + Integer.parseInt(in));
} catch (NumberFormatException | NullPointerException e) {
System.out.println("bad input " + in + " -> " + e.getClass().getSimpleName());
}
}
}
}
Output
open database
open logfile
send database: SELECT 1
send logfile: query sent
close logfile
close database
---
open printer
close printer
caught: empty message
---
length 2, value 10
bad input abc -> NumberFormatException
bad input null -> NullPointerException
- Objects declared in the brackets after
trymust implementAutoCloseable. Java calls theirclose()method automatically when the block ends. - Several resources are closed in reverse order: the log file opened last is closed first.
- When an exception is thrown, the resource is closed before the
catchblock runs, so “close printer” appears before “caught”. - Multi-catch handles several exception types with one block, joined by
|.
Catch order matters
Put specific exceptions before general ones. If catch (Exception e) came first, the more specific blocks after it could never run, and the compiler reports an error.
Common Mistakes
- Catching and ignoring:
catch (Exception e) {}hides real problems. At least log the message. - Losing the cause when wrapping an exception.
- Closing resources by hand in
finally, which is long and easy to get wrong. Use try-with-resources. - Making every custom exception checked. Too many forced
throwsclutter code; use unchecked exceptions for bugs.
Practice Exercises
Exercise 1. Write an unchecked exception InvalidMarksException and a method that throws it when marks are outside 0–100.
Show answer
class InvalidMarksException extends RuntimeException {
InvalidMarksException(int marks) {
super("Marks must be 0-100, got " + marks);
}
}
static void record(int marks) {
if (marks < 0 || marks > 100) throw new InvalidMarksException(marks);
System.out.println("Saved " + marks);
}
Exercise 2. In the try-with-resources example, what would print if you opened three connections A, B and C in one try-with-resources and no exception occurred?
Show answer
open A, open B, open C, then the body, then close C, close B, close A: resources close in reverse order of opening.
Frequently Asked Questions
What happens if close() also throws an exception?
If the body already threw an exception, the one from close() is attached to it as a suppressed exception, which you can read with getSuppressed(). The original exception is not lost.
Should my exception class names end with Exception?
Yes. It is a strong Java convention, and it tells readers immediately what the class is for.
Summary
- Extend
Exceptionfor checked andRuntimeExceptionfor unchecked custom exceptions. - Give exceptions clear messages and useful fields; keep the cause when wrapping.
- Try-with-resources closes
AutoCloseableobjects automatically, in reverse order. - Catch specific exceptions first; use multi-catch for shared handling.
