Exceptions
Things go wrong: files are missing, users type letters into number fields, networks fail. Java reports problems with exceptions, objects that describe what went wrong and travel up through your methods until something handles them.
An uncaught exception
public class Main {
static int parseAge(String text) {
return Integer.parseInt(text);
}
public static void main(String[] args) {
System.out.println(parseAge("31"));
System.out.println(parseAge("thirty"));
System.out.println("never printed");
}
}31 Exception in thread "main" java.lang.NumberFormatException: For input string: "thirty" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:565) at java.base/java.lang.Integer.parseInt(Integer.java:662) at Main.parseAge(Main.java:3) at Main.main(Main.java:8)
(The line numbers inside java.base vary between Java versions.) The stack trace shows the exception type, its message, and the chain of method calls, most recent first. Scan down for the first line in your code (Main.parseAge(Main.java:3)): that's usually where to look.
try / catch / finally
public class Main {
static int parseAgeOrDefault(String text) {
try {
return Integer.parseInt(text.trim());
} catch (NumberFormatException e) {
System.out.println("Not a number: " + text);
return -1;
} finally {
System.out.println("(checked \"" + text + "\")"); // always runs
}
}
public static void main(String[] args) {
System.out.println(parseAgeOrDefault(" 42 "));
System.out.println(parseAgeOrDefault("forty"));
}
}(checked " 42 ") 42 Not a number: forty (checked "forty") -1
You can catch several types, in separate blocks or combined with |:
public class Main {
public static void main(String[] args) {
String[] inputs = {"10", "0", "abc", null};
for (String in : inputs) {
try {
int n = Integer.parseInt(in);
System.out.println(100 / n);
} catch (ArithmeticException e) {
System.out.println("Can't divide by zero");
} catch (NumberFormatException | NullPointerException e) {
System.out.println("Bad input: " + e.getClass().getSimpleName());
}
}
}
}10 Can't divide by zero Bad input: NumberFormatException Bad input: NumberFormatException
(Integer.parseInt(null) throws NumberFormatException, not NullPointerException: always check what an API actually throws.)
Checked and unchecked exceptions
Java has two kinds of exceptions:
| Checked | Unchecked | |
|---|---|---|
| Extends | Exception |
RuntimeException |
| Examples | IOException, SQLException |
NullPointerException, IllegalArgumentException, NumberFormatException |
| Meaning | Expected problems outside your control | Usually bugs, or invalid arguments |
| The compiler… | forces you to catch them or declare throws |
doesn't require handling |
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
static String readConfig(Path path) throws IOException { // "callers must deal with this"
return Files.readString(path);
}
public static void main(String[] args) {
try {
System.out.println(readConfig(Path.of("missing-config.txt")));
} catch (IOException e) {
System.out.println("Could not read config: " + e.getClass().getSimpleName() + " " + e.getMessage());
}
}
}Could not read config: NoSuchFileException missing-config.txt
Remove the try/catch and the program won't even compile: unreported exception IOException; must be caught or declared to be thrown.
Throwing exceptions
Validate input and fail fast with a clear message:
class BankAccount {
private double balance;
void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive, got " + amount);
}
if (amount > balance) {
throw new IllegalStateException("Insufficient funds: balance " + balance + ", requested " + amount);
}
balance -= amount;
}
}
public class Main {
public static void main(String[] args) {
BankAccount acct = new BankAccount();
try {
acct.withdraw(-5);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
try {
acct.withdraw(100);
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}Amount must be positive, got -5.0 Insufficient funds: balance 0.0, requested 100.0
Custom exceptions
Create your own exception types for errors that are meaningful in your domain:
class PaymentDeclinedException extends Exception {
private final String reason;
PaymentDeclinedException(String reason) {
super("Payment declined: " + reason);
this.reason = reason;
}
String reason() { return reason; }
}
public class Main {
static void charge(String card, double amount) throws PaymentDeclinedException {
if (card.endsWith("0000")) throw new PaymentDeclinedException("card blocked");
if (amount > 1000) throw new PaymentDeclinedException("limit exceeded");
System.out.println("Charged " + amount + " to " + card);
}
public static void main(String[] args) {
String[][] attempts = { {"4242", "50"}, {"0000", "20"}, {"4242", "5000"} };
for (String[] a : attempts) {
try {
charge(a[0], Double.parseDouble(a[1]));
} catch (PaymentDeclinedException e) {
System.out.println(e.getMessage() + " (reason code: " + e.reason() + ")");
}
}
}
}Charged 50.0 to 4242 Payment declined: card blocked (reason code: card blocked) Payment declined: limit exceeded (reason code: limit exceeded)
try-with-resources
Anything that must be closed (files, database connections, network sockets) implements AutoCloseable. Declare it in try (...) and Java closes it automatically, even when an exception occurs:
class Connection implements AutoCloseable {
private final String name;
Connection(String name) { this.name = name; System.out.println("open " + name); }
void query(String sql) {
if (sql.contains("DROP")) throw new IllegalStateException("not allowed: " + sql);
System.out.println("run: " + sql);
}
@Override public void close() { System.out.println("close " + name); }
}
public class Main {
public static void main(String[] args) {
try (Connection db = new Connection("shop-db")) {
db.query("SELECT * FROM orders");
db.query("DROP TABLE orders");
} catch (IllegalStateException e) {
System.out.println("error: " + e.getMessage());
}
}
}open shop-db run: SELECT * FROM orders close shop-db error: not allowed: DROP TABLE orders
Notice the connection was closed before the catch block ran.
Good practice
- Catch specific exceptions you can actually handle. Don't
catch (Exception e)everywhere. - Never swallow exceptions silently (
catch (Exception e) {}): at least log them. - Fail fast: validate arguments early with clear messages.
- When rethrowing, keep the cause:
throw new ServiceException("Order failed", e);. The original stack trace is preserved. - Use exceptions for exceptional situations, not for normal control flow.
Practice
- Write
static double safeDivide(double a, double b)that throwsIllegalArgumentExceptionwhenbis 0, and call it inside a try/catch. - Create an
InsufficientStockException(checked) and aWarehouse.remove(String item, int qty)method that throws it. - Read a number from a string array of inputs, skipping invalid ones, and print the sum of the valid numbers.
1.When does a finally block run?
2.What's special about checked exceptions like IOException?
3.What does try-with-resources guarantee?