Sub topic 9
Writing Your Own Exception Classes
Java comes with many exception types, such as IllegalArgumentException and IOException. Sometimes none of them describes your problem well. You can then write your own exception class. A custom exception is a class you write that extends one of Java's exception classes.
Why Write Your Own?
Suppose a bank account cannot pay out more money than it holds. You could throw a plain Exception with a message. But a caller would then have to read the message text to learn what went wrong. A class named InsufficientFundsException says it in the type itself. Callers can catch exactly that type and handle it.
Choosing a Parent Class
Your class must extend some class in the Throwable family. Pick the parent based on how callers should treat the problem.
| Extend | Kind | Use it when |
|---|---|---|
| `Exception` | Checked | The caller can expect the problem and should plan for it |
| `RuntimeException` | Unchecked | The problem comes from a bug, such as a bad argument |
A checked exception is one the compiler makes you catch or declare with throws. Running out of money is a normal business event, so a checked exception fits it.
Writing the Class
A custom exception is usually short. It needs constructors, and each constructor passes its values up to the parent with super(...).
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
public InsufficientFundsException(String message, Throwable cause) {
super(message, cause);
}
}The first constructor takes a message. The second also takes a cause, which is another exception that led to this one. The next chapter covers causes in detail.
Using It
Save this in a file named BankDemo.java, next to InsufficientFundsException.java:
class Account {
private long balance;
Account(long balance) {
this.balance = balance;
}
void withdraw(long amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
if (amount > balance) {
throw new InsufficientFundsException(
"balance " + balance + " is less than " + amount);
}
balance -= amount;
}
}
public class BankDemo {
public static void main(String[] args) {
Account account = new Account(100);
try {
account.withdraw(30);
System.out.println("Withdrew 30");
account.withdraw(500);
} catch (InsufficientFundsException e) {
System.out.println("Sorry: " + e.getMessage());
}
}
}Compile and run:
javac InsufficientFundsException.java BankDemo.java
java BankDemoOutput:
Withdrew 30
Sorry: balance 70 is less than 500Look at the two checks in withdraw. The custom checked exception has to appear in the throws clause. IllegalArgumentException is unchecked, so it needs no declaration. A negative amount means the caller has a bug, and an unchecked exception fits that case.
Exercises
Exercise
Write a custom unchecked exception named InvalidAgeException with a constructor that takes a message. Which class should it extend?
Show answer
It should extend RuntimeException, because unchecked exceptions extend RuntimeException. Code: public class InvalidAgeException extends RuntimeException { public InvalidAgeException(String message) { super(message); } }
Exercise
If you delete throws InsufficientFundsException from the withdraw method, what happens when you compile?
Show answer
The code does not compile. InsufficientFundsException extends Exception, so it is checked, and the compiler requires the method to declare it or catch it.