7.2 Custom Exceptions
Built-in exceptions handle many general errors, but real projects often have business-rule failures. "Out of stock" is not a Java syntax error or a type error; it is a violated business rule.
Defining an Exception Class
Custom exceptions often inherit from Exception. In Java, a custom class usually passes its message to the parent constructor with super(message).
class OutOfStockException extends Exception {
OutOfStockException(String message) {
super(message);
}
}The message can be passed when throwing it:
throw new OutOfStockException("Notebook is out of stock.");The exception name should clearly express the error. OutOfStockException is more specific and easier for callers to recognize than a generic Exception.
Stock Example
class OutOfStockException extends Exception {
OutOfStockException(String message) {
super(message);
}
}
class Product {
String name;
int stock;
Product(String name, int stock) {
this.name = name;
this.stock = stock;
}
void purchase(int quantity) throws OutOfStockException {
if (quantity <= 0) {
throw new IllegalArgumentException("Quantity must be greater than 0.");
}
if (quantity > stock) {
throw new OutOfStockException(name + " is out of stock.");
}
stock -= quantity;
}
}
public class StockDemo {
public static void main(String[] args) {
Product product = new Product("Notebook", 5);
try {
product.purchase(3);
System.out.println("Purchase succeeded. Remaining stock: " + product.stock);
product.purchase(4);
} catch (OutOfStockException error) {
System.out.println("Purchase failed: " + error.getMessage());
}
}
}Output:
Purchase succeeded. Remaining stock: 2
Purchase failed: Notebook is out of stock.In this example, IllegalArgumentException means the argument itself is unreasonable, while OutOfStockException means a business rule blocks the purchase. Different exceptions express different problems, so caller code can respond more accurately.
Why Custom Exceptions Matter
The value of custom exceptions is not merely that they can throw errors. They give errors semantics.
When caller code catches OutOfStockException, it knows the problem is stock-related and can show business actions such as restocking or choosing another product. When it catches IllegalArgumentException, it is more likely to ask the user to change the quantity.