How do you create a custom exception in Java, and what information should it carry?
You extend one of the two base classes. Extend Exception when you want a checked exception, and extend RuntimeException when you want an unchecked one.
Then you give it the information that a caller needs to understand the failure. At the very least that is a message that says what went wrong. Often it is also the details of the failure, such as which record failed or which value was wrong.
public class Main {
public static void main(String[] args) {
try {
withdraw(50);
} catch (InsufficientFundsException e) {
System.out.println("problem : " + e.getMessage());
System.out.println("short by : " + e.getShortfall());
}
}
static void withdraw(int amount) {
int balance = 20;
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
}
}
class InsufficientFundsException extends Exception {
private final int shortfall;
InsufficientFundsException(int shortfall) {
super("there is not enough money, you are short by " + shortfall);
this.shortfall = shortfall;
}
int getShortfall() {
return this.shortfall;
}
}
There are three things to get right.
The first one is that the class name ends with Exception, so that everybody can tell what it is without reading it.
The second one is that you call the parent constructor with the message, using the call super(...). That sets the message, and it also makes sure that the stack trace of the exception points at the place where the exception was created.
The third one is that the extra information is kept in its own field, with a method to read it. The message is for people and the field is for the program, and it is much better to give the caller a number it can work with than to make it read the message to find out how bad the problem was.
One more thing is worth knowing. The exception class itself should be public if the caller is in a different package, and the constructors that take the extra details should be public as well.
The last question in this topic looks at the cause of an exception.