Skip to main content
Exception handling · Topic 5 of 7

Custom exceptions

Definition​

A custom exception is your own exception class, named after the problem, such as InsufficientFundsException. It can carry extra data so the caller knows exactly what went wrong.

Example code​

An exception that carries the missing amount

class InsufficientFundsException extends Exception {
private final long missing;

InsufficientFundsException(long missing) {
super("Missing " + missing + " to complete the payment");
this.missing = missing;
}

long missing() { return missing; }
}

class Wallet {
private long balance = 500;

void pay(long amount) throws InsufficientFundsException {
if (amount > balance) throw new InsufficientFundsException(amount - balance);
balance -= amount;
}
}

class Demo {
public static void main(String[] args) {
Wallet wallet = new Wallet();
try {
wallet.pay(800);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
System.out.println("Top up at least " + e.missing());
}
}
}

// Output:
// Missing 300 to complete the payment
// Top up at least 300

Finished this page? Track your progress (saved only in your browser).