Introduction
Programs meet problems they cannot ignore: a user types letters where a number belongs, a file is missing, a division by zero sneaks in. Java reports such problems by throwing an exception, an object describing what went wrong. If nothing catches it, the program stops with a stack trace. With try and catch you decide what happens instead: ask again, skip the bad line, or report a clear message.
How it works
Put code that can fail in a try block, followed by one or more catch blocks:
try {
int n = Integer.parseInt(text);
System.out.println(100 / n);
} catch (NumberFormatException e) {
System.out.println("not a number");
} catch (ArithmeticException e) {
System.out.println("cannot divide by zero");
} finally {
System.out.println("done");
}
When an exception is thrown, Java skips the rest of the try block and runs the first catch whose type matches. e.getMessage() gives its message. The finally block runs in every case, which makes it the place to release resources. Order catches from most specific to most general, because catch (Exception e) matches almost everything.
Exceptions form a class hierarchy. Unchecked exceptions extend RuntimeException: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException, IllegalArgumentException. They usually mean a bug or bad input, and the compiler does not force you to handle them. Checked exceptions, such as IOException, must be either caught or declared in the method's signature with throws; otherwise the code does not compile.
You can throw exceptions yourself: throw new IllegalArgumentException("age must be positive");. To create your own, extend Exception (checked) or RuntimeException (unchecked) and pass the message to super. A method that throws a checked exception declares it: static int withdraw(int b, int a) throws InsufficientFundsException. Every caller then has to deal with it.
For resources such as files, Java has try-with-resources: try (Scanner sc = new Scanner(file)) { ... } closes the resource automatically, even when an exception happens.
Example
import java.util.Scanner;
public class Main {
// A checked exception of our own: callers must catch it or declare it.
static class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
static int withdraw(int balance, int amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("short by " + (amount - balance));
}
return balance - amount;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int balance = 100;
while (in.hasNextLine()) {
String line = in.nextLine();
try {
int amount = Integer.parseInt(line);
balance = withdraw(balance, amount);
System.out.println("ok, balance " + balance);
} catch (NumberFormatException e) {
System.out.println("not a number: " + line);
} catch (InsufficientFundsException e) {
System.out.println("refused: " + e.getMessage());
} finally {
System.out.println("-- handled " + line);
}
}
}
}Input used: 30 ⏎ ten ⏎ 90 ⏎ 50
Line by line
InsufficientFundsExceptionextendsException, so it is checked.withdrawthrows it when the amount is too large, and declares it withthrows.- Each input line goes through
parseInt, which throwsNumberFormatExceptionfor "ten". - Each kind of failure has its own
catch, andfinallyprints after every line, whatever happened.
Expected result
With this input:
30
ten
90
50
it prints:
ok, balance 70
-- handled 30
not a number: ten
-- handled ten
refused: short by 20
-- handled 90
ok, balance 20
-- handled 50
In the real world
Web servers catch exceptions per request, so one bad request returns an error page instead of stopping the server. Libraries throw well-named exceptions, such as FileNotFoundException, so callers can react precisely. Logging the exception's message and stack trace is the first step in diagnosing most production problems.
Common mistakes
- Catching Exception and doing nothing, which hides real bugs.
- Using exceptions for normal control flow, such as ending a loop.
- Catching a general type before a specific one, which makes the later catch unreachable and is a compile error.
- Throwing exceptions without a message, which makes problems hard to diagnose.
Best practices
- Catch the most specific exception you can handle, and let the rest propagate.
- Validate input early and throw
IllegalArgumentExceptionwith a clear message. - Use try-with-resources for anything that must be closed.
Summary
Exceptions report errors by interrupting normal flow until a matching catch handles them; finally always runs. Checked exceptions must be caught or declared with throws, unchecked ones extend RuntimeException. You can throw built-in exceptions with clear messages or define your own by extending Exception or RuntimeException.
Quick check
Key takeaways
- Wrap code that can fail in try, handle each kind of failure in its own catch, and clean up in finally.
- Checked exceptions must be caught or declared; unchecked ones usually signal a bug to fix.
- Throw exceptions with clear messages, and create your own class when the error belongs to your program.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.