These are the notes for Java episode 27. In episode 26 we caught exceptions that Java threw at us. Today we throw our own: our bank gets an InsufficientFundsException that says how much money is missing, we learn the difference between throw and throws, how an exception travels up through methods, how to choose checked or unchecked, and finally try-with-resources, which closes files (and anything AutoCloseable) for us. Every example was run with javac 21.
The problem: the ATM that lies
Ravi has 5,000 rupees and asks the ATM for 8,000. The withdraw method from episode 25 refuses by returning false, but the ATM code never checks it:
class Account {
private double balance;
Account(double balance) { this.balance = balance; }
boolean withdraw(double amount) {
if (amount > balance) return false;
balance -= amount;
return true;
}
double getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
Account a = new Account(5000);
a.withdraw(8000);
System.out.println("Cash given: 8000");
System.out.println("Balance: " + a.getBalance());
}
}
Cash given: 8000
Balance: 5000.0
The account refused correctly, but the screen lied, because a boolean is just a value and values can be ignored. The fix from episode 26: an exception, an alarm that stops the program unless someone handles it.
throw: raise the alarm yourself
class Account {
private double balance;
Account(double balance) { this.balance = balance; }
void withdraw(double amount) {
if (amount <= 0)
throw new IllegalArgumentException("Amount must be positive: " + amount);
if (amount > balance)
throw new IllegalStateException("Balance is only " + balance);
balance -= amount;
}
}
public class Main {
public static void main(String[] args) {
Account a = new Account(5000);
a.withdraw(8000);
System.out.println("Cash given: 8000");
}
}
Exception in thread "main" java.lang.IllegalStateException: Balance is only 5000.0
at Account.withdraw(Main.java:9)
at Main.main(Main.java:17)
throw new SomeException("reason")creates an exception object and throws it. The method stops at once;balance -= amountnever runs.IllegalArgumentException: the value you passed is wrong (a negative amount).IllegalStateException: the value is fine, but the object's current state doesn't allow it (not enough balance).- Both are unchecked (
RuntimeExceptionchildren), so no extra declaration is needed.
The remaining problem: the ATM sees "some IllegalStateException". It can't tell insufficient funds apart from any other state problem, and it can't ask short by how much?
Our own exception class
| In real life | In Java |
|---|---|
| A plain bell: something is wrong, somewhere | IllegalStateException: a general problem |
| "Smoke alarm, room 204": what and where | InsufficientFundsException: a class we write |
| A bounced-cheque slip: "short by 3,000" | getShortBy(): extra fields with details |
Exceptions are just classes, so we use inheritance:
class InsufficientFundsException extends Exception {
private final double shortBy;
InsufficientFundsException(double shortBy) {
super("Short by " + shortBy + " rupees");
this.shortBy = shortBy;
}
double getShortBy() { return shortBy; }
}
extends Exceptionmakes it a checked exception.super(message)passes the message to the parent constructor (episode 18), sogetMessage()works.- Extra fields (
shortBy) carry details the caller can use. - By convention the class name ends in
Exception.
Throwing it without any other change:
void withdraw(double amount) {
if (amount > balance)
throw new InsufficientFundsException(amount - balance);
balance -= amount;
}
Main.java:16: error: unreported exception InsufficientFundsException; must be caught or declared to be thrown
throw new InsufficientFundsException(amount - balance);
^
1 error
It's checked, just like FileNotFoundException last episode.
throws: pass it up to the caller
The account is not the right place to decide what the ATM screen shows, so withdraw declares the exception:
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance)
throw new InsufficientFundsException(amount - balance);
balance -= amount;
}
Now the error moves to the caller:
Main.java:24: error: unreported exception InsufficientFundsException; must be caught or declared to be thrown
a.withdraw(8000);
^
1 error
throws is a warning label on the method: "calling me can raise this". The compiler makes sure somebody, somewhere, decides what happens. The ATM catches it:
class InsufficientFundsException extends Exception {
private final double shortBy;
InsufficientFundsException(double shortBy) {
super("Short by " + shortBy + " rupees");
this.shortBy = shortBy;
}
double getShortBy() { return shortBy; }
}
class Account {
private double balance;
Account(double balance) { this.balance = balance; }
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance)
throw new InsufficientFundsException(amount - balance);
balance -= amount;
}
double getBalance() { return balance; }
}
public class Main {
public static void main(String[] args) {
Account a = new Account(5000);
try {
a.withdraw(8000);
System.out.println("Cash given: 8000");
} catch (InsufficientFundsException e) {
System.out.println("ATM: " + e.getMessage());
System.out.println("Try " + (8000 - e.getShortBy()) + " instead");
}
System.out.println("Balance: " + a.getBalance());
}
}
ATM: Short by 3000.0 rupees
Try 5000.0 instead
Balance: 5000.0
A precise name to catch, and fields with details: that's what a custom exception gives you.
throw vs throws
throw |
throws |
|
|---|---|---|
| Where | inside a method body | in the method signature |
| What follows | one exception object (new ...) |
one or more exception types, comma-separated |
| Meaning | raise this exception now | this method may raise these |
| Example | throw new InsufficientFundsException(3000); |
void withdraw(double a) throws InsufficientFundsException |
Propagation: the alarm passes up
public class Main {
static void level3() throws Exception {
throw new Exception("from level 3");
}
static void level2() throws Exception {
level3();
}
static void level1() throws Exception {
level2();
}
public static void main(String[] args) {
try {
level1();
} catch (Exception e) {
System.out.println("main caught: " + e.getMessage());
}
}
}
main caught: from level 3
The exception travels through methods that only declare it until it reaches one that catches it. If main also declared throws and nobody caught it, the JVM would print the stack trace and stop.
Checked or unchecked custom exceptions?
Extend RuntimeException instead, and nobody is forced to handle it:
class InsufficientFundsException extends RuntimeException {
InsufficientFundsException(String message) {
super(message);
}
}
public class Main {
static void withdraw(double balance, double amount) {
if (amount > balance)
throw new InsufficientFundsException("Short by " + (amount - balance));
}
public static void main(String[] args) {
withdraw(5000, 8000);
}
}
Exception in thread "main" InsufficientFundsException: Short by 3000.0
at Main.withdraw(Main.java:10)
at Main.main(Main.java:13)
A common guideline:
| Situation | Choose | Example |
|---|---|---|
| A careful caller can still hit it and can recover | checked (extends Exception) |
low balance, missing file |
| It means the caller wrote a bug | unchecked (extends RuntimeException) |
negative amount, null argument |
Many modern libraries prefer unchecked exceptions for almost everything. Either is fine if the choice is deliberate.
The clean-up problem
Files, network and database connections borrow something from the operating system until you call close(). If an exception happens before close(), it's skipped and the resource leaks. With finally it looks like this:
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter out = new FileWriter("passbook.txt");
out.write("Deposit 5000\n");
out.write("Withdraw 2000\n");
out.close();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("passbook.txt"));
System.out.println(in.readLine());
System.out.println(in.readLine());
} finally {
if (in != null) in.close();
}
}
}
Deposit 5000
Withdraw 2000
Eight lines of ceremony for two lines of reading, a null check, and the writer isn't even protected. (throws IOException on main passes the checked input/output exception up to the JVM to keep the demo short. FileNotFoundException is a child of IOException.)
try-with-resources
Since Java 7, put the resource in brackets after try:
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try (FileWriter out = new FileWriter("passbook.txt")) {
out.write("Deposit 5000\n");
out.write("Withdraw 2000\n");
}
try (BufferedReader in = new BufferedReader(new FileReader("passbook.txt"))) {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
}
}
Deposit 5000
Withdraw 2000
When the try block ends, normally or by an exception, Java calls close() for you. readLine() returns null at the end of the file.
AutoCloseable: what can go in the brackets
Any class that implements AutoCloseable (one method: close()):
class Locker implements AutoCloseable {
private final String name;
Locker(String name) {
this.name = name;
System.out.println(name + " opened");
}
public void close() {
System.out.println(name + " closed");
}
}
public class Main {
public static void main(String[] args) {
try (Locker a = new Locker("Locker A");
Locker b = new Locker("Locker B")) {
System.out.println("Counting cash...");
int notes = 500 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}
Locker A opened
Locker B opened
Counting cash...
Locker B closed
Locker A closed
Caught: / by zero
- Several resources are separated by
;. - They close in reverse order (B, then A), like stacking plates.
- They close before the catch block runs, even when an exception flies.
Without implements AutoCloseable, a method named close is not enough:
Main.java:14: error: incompatible types: try-with-resources not applicable to variable type
try (Locker a = new Locker("Locker A");
^
(Locker cannot be converted to AutoCloseable)
Common mistakes (and the real error messages)
| Mistake | Real message | Why | Fix |
|---|---|---|---|
Throwing a checked exception without throws |
error: unreported exception InsufficientFundsException; must be caught or declared to be thrown |
checked exceptions must be declared | add throws InsufficientFundsException |
Calling a throws method without handling |
same message, on the caller's line | the caller must decide too | try/catch, or declare throws |
throw new Exception("oops"); in main |
error: unreported exception Exception; must be caught or declared to be thrown |
Exception itself is checked |
throw a specific type and declare it |
Resource that isn't AutoCloseable |
error: incompatible types: try-with-resources not applicable to variable type |
no AutoCloseable promise |
implements AutoCloseable |
throws instead of throw (or the reverse) |
error: illegal start of expression (for throws new ... inside a method) |
wrong keyword in the wrong place | throw + object inside; throws + types in the signature |
Returning false for errors |
no error; Cash given: 8000 |
return values can be ignored | throw an exception |
Mini project: a safe ATM session
class InsufficientFundsException extends Exception {
private final double shortBy;
InsufficientFundsException(double shortBy) {
super("Short by " + shortBy + " rupees");
this.shortBy = shortBy;
}
double getShortBy() { return shortBy; }
}
class Account {
private double balance;
Account(double balance) { this.balance = balance; }
void withdraw(double amount) throws InsufficientFundsException {
if (amount <= 0 || amount % 100 != 0)
throw new IllegalArgumentException("Amount must be a positive multiple of 100: " + amount);
if (amount > balance)
throw new InsufficientFundsException(amount - balance);
balance -= amount;
}
double getBalance() { return balance; }
}
class AtmSession implements AutoCloseable {
AtmSession() { System.out.println("Card inserted"); }
public void close() { System.out.println("Card returned"); }
}
public class Main {
public static void main(String[] args) {
Account a = new Account(5000);
double[] requests = { 2000, 450, 4000, 3000 };
try (AtmSession s = new AtmSession()) {
for (double r : requests) {
try {
a.withdraw(r);
System.out.println("Cash given: " + r);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage() + "; max now " + a.getBalance());
} catch (IllegalArgumentException e) {
System.out.println("Invalid: " + e.getMessage());
}
}
}
System.out.println("Balance: " + a.getBalance());
}
}
Card inserted
Cash given: 2000.0
Invalid: Amount must be a positive multiple of 100: 450.0
Short by 1000.0 rupees; max now 3000.0
Cash given: 3000.0
Card returned
Balance: 0.0
Practice
- Write
InvalidAgeExceptionand throw it for an age outside 0-120. - Make it checked, then unchecked. What changes in the calling code?
- Write a
Tapclass that implementsAutoCloseableand prints "Tap closed". - Write three lines to
notes.txtand read them back, both with try-with-resources.
Solutions
1 and 2. Checked version: setAge must declare throws InvalidAgeException, and every caller must catch or declare it. Change extends Exception to extends RuntimeException and the throws clauses and the forced try/catch go away; the code still compiles without them.
class InvalidAgeException extends Exception {
InvalidAgeException(int age) { super("Invalid age: " + age); }
}
static void setAge(int age) throws InvalidAgeException {
if (age < 0 || age > 120) throw new InvalidAgeException(age);
System.out.println("Age set: " + age);
}
3.
class Tap implements AutoCloseable {
Tap() { System.out.println("Tap open"); }
public void close() { System.out.println("Tap closed"); }
}
// try (Tap t = new Tap()) { System.out.println("Filling bucket"); }
// prints: Tap open, Filling bucket, Tap closed
4. Same shape as the passbook example: one try (FileWriter out = ...) that writes three lines, then one try (BufferedReader in = ...) with a while ((line = in.readLine()) != null) loop; main declares throws IOException.
Quick quiz
class LowBalance extends RuntimeException {
LowBalance(String m) { super(m); }
}
static void pay(int bal) {
if (bal < 100) throw new LowBalance("need 100");
System.out.print("paid ");
}
// in main:
try { pay(50); } catch (LowBalance e) {
System.out.print(e.getMessage());
}
A) Compile error: pay needs throws B) paid need 100 C) need 100 D) paid
Answer
C. LowBalance extends RuntimeException, so it's unchecked and needs no throws. pay(50) throws before paid is printed, and the catch prints the message.
Interview questions
- throw vs throws?
throwraises one exception object inside a method;throwsin the signature declares which exception types the method may pass to its caller. - How do you create a custom exception? Extend
Exception(checked) orRuntimeException(unchecked), pass the message tosuper, and add fields for details. - When should a custom exception be checked? When a correct caller can still hit the condition and is expected to recover (insufficient funds, missing file). Programming errors should be unchecked.
- What is exception propagation? An uncaught exception moves up the call stack, method by method, until a matching catch handles it or the program ends.
- What is try-with-resources? A
try (...)that automatically callsclose()on every declared resource when the block ends, normally or by exception, in reverse order of opening. - What can be used in try-with-resources? Any object whose class implements
AutoCloseable(or its childCloseable). - IllegalArgumentException vs IllegalStateException? The first means a bad argument value; the second means the object's current state doesn't allow the operation.
- What happens if close() also throws? The exception from the try block is kept as the main one, and the close() exception is attached to it as a suppressed exception (
e.getSuppressed()).
Glossary
| Term | Meaning | Example |
|---|---|---|
| throw | A statement that raises one exception object | throw new IllegalStateException("...") |
| throws | A clause declaring exceptions a method may pass up | void withdraw(double a) throws InsufficientFundsException |
| Custom exception | An exception class you write | class InsufficientFundsException extends Exception |
| super(message) | Passing the message to the parent exception's constructor | super("Short by 3000.0 rupees") |
| IllegalArgumentException | Unchecked: a method got a bad argument | a negative amount |
| IllegalStateException | Unchecked: the object's state forbids the call | not enough balance |
| Propagation | An exception moving up to the caller | level3 → level2 → level1 → main |
| Checked exception | Must be caught or declared | extends Exception |
| Unchecked exception | Not enforced by the compiler | extends RuntimeException |
| Resource | Something borrowed from the OS that must be closed | a file, a network connection |
| Resource leak | A resource that was never closed | close() skipped by an exception |
| try-with-resources | try (...) that closes its resources automatically |
try (FileWriter out = ...) |
| AutoCloseable | Interface with one method, close() |
class Locker implements AutoCloseable |
| IOException | Checked parent of input/output problems | FileNotFoundException |
| FileWriter | Writes characters to a file | new FileWriter("passbook.txt") |
| BufferedReader | Reads text a line at a time | in.readLine() |
| Suppressed exception | An exception from close() attached to the main one |
e.getSuppressed() |
Summary
- Returning
falselets errors be ignored;throwan exception instead. - A custom exception (
extends ExceptionorRuntimeException) gives a precise name to catch and fields with details. throwsdeclares a checked exception and passes it up; the compiler makes sure someone handles it.- throw = an object, now. throws = types, in the signature.
- Recoverable → checked; caller's bug → unchecked.
- try-with-resources closes anything
AutoCloseable, in reverse order, even when an exception flies. - Next: an
intcan't be null and can't go into anArrayList. Episode 28: wrapper classes and autoboxing.