Adding Custom Fields and Methods
What you'll learn: You'll learn how to enrich your custom exceptions with domain-specific data and behavior that helps diagnose and handle errors more effectively.
Why Add Custom Fields?
Basic exceptions provide a message and stack trace, but sometimes you need more context. Imagine a PaymentFailedException — wouldn't it be helpful to know the payment amount, the transaction ID, and when it failed? Custom fields turn generic exceptions into rich diagnostic tools.
Think of it like a doctor's medical report: instead of just saying "patient is sick," the report includes temperature, blood pressure, and symptoms. Your custom exception should do the same for errors.
Adding Domain-Specific Fields
When you extend Exception or RuntimeException, you can add any fields that provide useful context:
public class PaymentFailedException extends Exception {
private final String transactionId;
private final double amount;
private final long timestamp;
public PaymentFailedException(String message, String transactionId, double amount) {
super(message);
this.transactionId = transactionId;
this.amount = amount;
this.timestamp = System.currentTimeMillis();
}
public String getTransactionId() {
return transactionId;
}
public double getAmount() {
return amount;
}
public long getTimestamp() {
return timestamp;
}
}
Now when you catch this exception, you can access specific details:
try {
processPayment(100.50, "TXN-12345");
} catch (PaymentFailedException e) {
System.out.println("Transaction " + e.getTransactionId() +
" failed for $" + e.getAmount());
// Log to audit system, notify user, etc.
}
Best Practices
Make fields final and private to keep exceptions immutable and safe. Provide getter methods for access. Add fields that help recovery or diagnosis, not unnecessary noise.
Key Takeaway: Custom fields transform exceptions from simple error messages into structured diagnostic data, giving handlers the information they need to respond appropriately.