An exception is an event that interrupts the normal flow of a program: text that is not a number, division by zero, a missing file. If nothing catches it, the program stops with a stack trace. Java’s try, catch and finally let you handle problems gracefully, and throw and throws let your own code report errors. Java also splits exceptions into checked and unchecked, which this lesson explains.
In this lesson you will learn
- How
try,catchandfinallywork - Catching different exception types separately
- Checked vs unchecked exceptions
- Throwing exceptions and declaring them with
throws - Writing your own exception class
try, catch and finally
public class Main {
public static void main(String[] args) {
String[] inputs = {"42", "abc", "0"};
for (String in : inputs) {
try {
int n = Integer.parseInt(in);
System.out.println("100 / " + n + " = " + (100 / n));
} catch (NumberFormatException e) {
System.out.println("Not a number: " + in);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} finally {
System.out.println("-- checked " + in);
}
}
}
}
Output
100 / 42 = 2
-- checked 42
Not a number: abc
-- checked abc
Cannot divide by zero
-- checked 0
- Code that might fail goes in the
tryblock. When an exception occurs, Java jumps straight to the firstcatchwhose type matches. Integer.parseInt("abc")throwsNumberFormatException; integer division by zero throwsArithmeticException.finallyruns every time, with or without an exception. It is the place for clean-up such as closing a file.
throw, throws and Custom Exceptions
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) { super(message); }
}
class Account {
private double balance;
Account(double balance) { this.balance = balance; }
void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0) throw new IllegalArgumentException("amount must be positive");
if (amount > balance) throw new InsufficientFundsException("need " + (amount - balance) + " more");
balance -= amount;
}
double getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
Account acc = new Account(500);
double[] requests = {200, -5, 900};
for (double r : requests) {
try {
acc.withdraw(r);
System.out.println("Withdrew " + r + ", balance " + acc.getBalance());
} catch (InsufficientFundsException e) {
System.out.println("Checked exception: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Unchecked exception: " + e.getMessage());
}
}
}
}
Output
Withdrew 200.0, balance 300.0
Unchecked exception: amount must be positive
Checked exception: need 600.0 more
throw new ...raises an exception from your own code.InsufficientFundsException extends Exception, so it is a checked exception. The method must declare it withthrows, and callers must catch it or declare it too; otherwise the code does not compile.IllegalArgumentExceptionextendsRuntimeException, so it is unchecked: the compiler does not force anyone to handle it.getMessage()returns the text passed to the constructor.
Checked vs Unchecked
| Checked | Unchecked | |
|---|---|---|
| Extends | Exception | RuntimeException |
| Compiler forces handling? | Yes | No |
| Typical cause | Outside problems: missing file, network down | Bugs: null reference, bad index, bad argument |
| Examples | IOException, SQLException | NullPointerException, ArrayIndexOutOfBoundsException |
Serious problems such as OutOfMemoryError extend Error and are not meant to be caught.
try-with-resources
Objects that must be closed (files, database connections) can be opened in the try brackets. Java closes them automatically, even after an exception:
try (var reader = new java.io.BufferedReader(new java.io.FileReader("data.txt"))) {
System.out.println(reader.readLine());
} catch (java.io.IOException e) {
System.out.println("Could not read file: " + e.getMessage());
}
Common Mistakes
- Catching
Exceptioneverywhere. It hides real bugs; catch the specific types you expect. - An empty catch block. At least log the problem.
- Catching a parent type before a child type, such as
ExceptionbeforeIOException. The compiler rejects the unreachable catch. - Using exceptions for normal control flow instead of a simple
ifcheck.
Practice Exercises
Exercise 1. Write safeParse(String s) that returns the number, or -1 if s is not a valid integer.
Show answer
static int safeParse(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return -1;
}
}
Exercise 2. Catch two exception types in one block.
Show answer
try {
// risky code
} catch (NumberFormatException | ArithmeticException e) {
System.out.println("Bad input: " + e.getMessage());
}
Frequently Asked Questions
What is the difference between throw and throws?
throw actually raises an exception inside a method. throws in a method’s signature warns callers which checked exceptions it may raise.
Does finally run if the try block returns?
Yes. finally runs before the method returns. It is skipped only in extreme cases such as System.exit().
Summary
tryholds risky code,catchhandles specific types, andfinallyalways runs.- Checked exceptions must be caught or declared; unchecked ones need not be.
throwraises;throwsdeclares.- Use try-with-resources for files and connections.
