Sub topic 9
Writing Your Own Exception Classes
Java comes with many ready-made exceptions, such as IllegalArgumentException and IOException. Sometimes none of them describes your problem well. A banking program might need to say "this account does not have enough money." A built-in exception can carry that message, but it cannot tell a reader what kind of problem happened just from its name.
A custom exception is an exception class that you write yourself. It lets your code report a specific problem by name. This chapter shows how to write one, how to choose its parent class, and how to add extra information to it.
Why Write Your Own Exception?
A custom exception helps in three ways:
- Clear meaning. The name
InsufficientFundsExceptiontells the reader what went wrong before they read the message. - Targeted catching. Callers can write
catch (InsufficientFundsException e)and handle only that problem. Other problems keep moving up the call stack. - Extra data. Your class can hold fields, such as how much money was missing. The caller can read those values instead of digging through a text message.
You do not need a custom exception for every error. If a built-in exception already fits, use it. For example, a negative argument is a good match for IllegalArgumentException.
The Smallest Custom Exception
A custom exception is an ordinary class that extends (inherits from) Exception or one of its subclasses. Here is a minimal one:
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}This class has no fields and only one constructor. A constructor is the special method that runs when you create an object with new. The line super(message) passes the message up to the parent class, Exception. Exception stores the message, and anyone can read it later with getMessage().
That is all you need. Because the class extends Exception, Java treats it like any other exception. You can throw it, catch it, and declare it with throws.
Choosing the Parent Class
The parent class you pick decides whether your exception is checked or unchecked. A checked exception must be caught or declared with throws, and the compiler enforces this. An unchecked exception has no such rule.
| Extend this class | Kind | Use it when |
|---|---|---|
| `Exception` | Checked | The caller can reasonably recover, and you want the compiler to make them think about it. Example: not enough money in an account. |
| `RuntimeException` | Unchecked | The problem comes from a programming mistake, such as a bad argument or a broken rule the caller should have followed. |
| `Error` or `Throwable` | Do not use | These are for serious problems inside the Java runtime itself, such as running out of memory. |
You can also extend a more specific built-in class. For example, class ConfigFileMissingException extends IOException makes your exception a kind of IOException. Any code that already catches IOException will catch yours too.
Adding Useful Constructors
The built-in Exception class has several constructors. Most custom exceptions copy two of them:
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
public InsufficientFundsException(String message, Throwable cause) {
super(message, cause);
}
}The second constructor takes a cause, which is another exception that led to this one. Storing a cause is called exception chaining. The next chapter covers it in detail. For now, add this constructor to your exceptions anyway, because it costs one short method and saves trouble later.
Adding Extra Information
A message is text written for people. Code that catches the exception often needs real values instead. You can add fields to your exception class, just like any other class.
Below is a full program you can run. Save it as BankDemo.java. It defines a checked exception with a shortfall field, an unchecked exception for bad amounts, and an Account class that uses both.
class InsufficientFundsException extends Exception {
private final long shortfall;
public InsufficientFundsException(String message, long shortfall) {
super(message);
this.shortfall = shortfall;
}
public InsufficientFundsException(String message, long shortfall, Throwable cause) {
super(message, cause);
this.shortfall = shortfall;
}
public long getShortfall() {
return shortfall;
}
}
class InvalidAmountException extends RuntimeException {
public InvalidAmountException(String message) {
super(message);
}
}
class Account {
private long balance;
Account(long openingBalance) {
this.balance = openingBalance;
}
long getBalance() {
return balance;
}
void withdraw(long amount) throws InsufficientFundsException {
if (amount <= 0) {
throw new InvalidAmountException("amount must be positive, got " + amount);
}
if (amount > balance) {
throw new InsufficientFundsException(
"balance " + balance + " is less than " + amount,
amount - balance);
}
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, balance is now " + account.getBalance());
account.withdraw(500);
System.out.println("This line is never reached");
} catch (InsufficientFundsException e) {
System.out.println("Could not withdraw: " + e.getMessage());
System.out.println("Short by: " + e.getShortfall());
}
try {
account.withdraw(-5);
} catch (InvalidAmountException e) {
System.out.println("Bad input: " + e.getMessage());
}
}
}Compile and run it:
javac BankDemo.java
java BankDemoThe output is:
Withdrew 30, balance is now 70
Could not withdraw: balance 70 is less than 500
Short by: 430
Bad input: amount must be positive, got -5Here is what is happening, step by step:
- The first withdrawal of 30 succeeds, and the balance drops to 70.
- The second withdrawal of 500 is too large.
withdrawcreates anInsufficientFundsExceptionand throws it, with a shortfall of 430. - Java skips the rest of the
tryblock and jumps to the matchingcatch. The caller reads both the message and the number. - The withdrawal of -5 throws
InvalidAmountException. It is unchecked, sowithdrawdoes not list it in itsthrowsclause. The caller catches it anyway because it chose to.
Notice the field is final. An exception describes something that already happened, so its data should not change after you create it.
Common Mistakes
- Making every exception checked. If callers can do nothing useful except crash, a checked exception forces them to write pointless
catchblocks. UseRuntimeExceptionfor programming mistakes. - Forgetting to call
super(message). Without that call,getMessage()returnsnull, and your stack traces lose their explanation. - Creating a new class for every tiny case.
NegativeAmountException,ZeroAmountException, andHugeAmountExceptioncan usually be a singleInvalidAmountExceptionwith a clear message. - Extending
ThrowableorErrordirectly. Ordinarycatch (Exception e)blocks miss these, which surprises other developers.
Exercises
Exercise
You are writing a library that loads user settings. If the settings file has a syntax error, the caller could show a friendly message and fall back to default settings. Should your SettingsFormatException extend Exception or RuntimeException? Why?
Show answer
Extend Exception, which makes it checked. The caller can recover by using defaults, and a checked exception makes the compiler remind every caller to handle the problem. You could also extend IOException, because a bad file is a kind of input problem.
Exercise
Write an unchecked exception class named InvalidAgeException with two constructors: one that takes a message, and one that takes a message and a cause.
Show answer
class InvalidAgeException extends RuntimeException { public InvalidAgeException(String message) { super(message); } public InvalidAgeException(String message, Throwable cause) { super(message, cause); } }
Exercise
A teammate writes public MyException(String message) { } with an empty body. What does new MyException("disk full").getMessage() return, and how do you fix it?
Show answer
It returns null, because the message was never passed to the parent class. Fix it by adding super(message); as the first line of the constructor.
Exercise
In BankDemo, change the opening balance to 600 and run the program again. What does it print, and why?
Show answer
It prints "Withdrew 30, balance is now 570", then "This line is never reached", then "Bad input: amount must be positive, got -5". With 570 in the account, the 500 withdrawal succeeds and no InsufficientFundsException is thrown, so the line after it runs. The -5 withdrawal still throws InvalidAmountException.