Overriding getMessage for Custom Formatting
What you'll learn: How to override the getMessage() method in custom exceptions to provide rich, formatted error messages that include your exception's custom field values.
Why Override getMessage()?
By default, getMessage() returns the simple string you passed to the exception's constructor. But when your custom exception has additional fields (like error codes, timestamps, or context data), you want those details visible in error messages without forcing callers to manually extract each field.
Think of it like customizing a receipt: the basic receipt shows just the total, but you can override the print format to include itemized details, tax breakdown, and store information—all automatically formatted.
How It Works
When you override getMessage() in your custom exception class, you control exactly what string gets returned. You can combine the original message with your custom fields to create informative, context-rich error messages:
public class InsufficientFundsException extends Exception {
private double balance;
private double requestedAmount;
public InsufficientFundsException(String message, double balance, double requestedAmount) {
super(message);
this.balance = balance;
this.requestedAmount = requestedAmount;
}
@Override
public String getMessage() {
return super.getMessage() +
" [Balance: $" + balance +
", Requested: $" + requestedAmount +
", Shortfall: $" + (requestedAmount - balance) + "]";
}
}
Now when this exception is caught and logged, the message automatically includes all context without extra work.
The Benefits
This approach means stack traces, log files, and error displays automatically show complete information. Developers debugging issues get immediate context without hunting through code to extract individual fields.
Key Takeaway: Override getMessage() in custom exceptions to automatically format and include custom field values in error messages, making exceptions self-documenting and debugging easier.