Custom Exceptions: Domain-Specific Error Signaling in Java
Choose Java custom exceptions for domain failures, preserve internal causes, and return stable error codes with localized safe messages at API boundaries.
Choose Java custom exceptions for domain failures, preserve internal causes, and return stable error codes with localized safe messages at API boundaries.
Custom Exceptions: Domain-Specific Error Signaling in Java
A custom exception gives a domain failure, such as an insufficient account balance, a type callers can handle directly. Use Java’s built-in exceptions when they already describe the problem.
Introduction
When an exception is thrown, normal control flow stops until a matching catch block handles it. Built-in types such as IllegalArgumentException, NullPointerException, and IOException cover common failures. A domain exception is useful when callers need a distinct category or structured context.
Use a custom type when callers need to distinguish a failure or inspect structured data. For routine invalid inputs, an existing exception such as IllegalArgumentException may be enough.
This article covers checked and unchecked custom exceptions, cause chaining, error codes, and mapping internal failures to safe API responses.
When to Use
Use custom exceptions when:
- Domain logic encounters an invalid state that violates business rules
- Standard Java exceptions do not convey enough meaning
- You want callers to catch specific application errors
- You need to associate additional data with a failure
- You are building a library or API consumed by others
import java.math.BigDecimal;
import java.util.Currency;
public class InsufficientFundsException extends Exception {
private static final long serialVersionUID = 1L;
private final BigDecimal available;
private final BigDecimal requested;
private final Currency currency;
public InsufficientFundsException(
BigDecimal available, BigDecimal requested, Currency currency) {
super("Withdrawal exceeds the available balance");
this.available = available;
this.requested = requested;
this.currency = currency;
}
public BigDecimal getAvailable() { return available; }
public BigDecimal getRequested() { return requested; }
public Currency getCurrency() { return currency; }
}
Create decimal amounts from strings, such as new BigDecimal("12.50"), instead of converting from double. The string constructor preserves the decimal value written in the source. Include a Currency when the amount’s currency is part of the domain; 12.50 alone does not identify its unit. See the Java SE 27 BigDecimal API and Currency API.
When NOT to Use
- Do not create custom exceptions for every error — Use standard exceptions when they fit
- Do not extend Exception without good reason — Consider RuntimeException for unchecked variants
- Do not create one-off exceptions — A custom exception should represent a real category of failure
- Do not create shallow exceptions — Empty subclasses of Exception add no value
Class Hierarchy Design
classDiagram
class Exception["java.lang.Exception"] {
<<checked>>
}
class RuntimeException["java.lang.RuntimeException"] {
<<unchecked>>
}
class ApplicationException {
+String code
}
class InsufficientFundsException {
+BigDecimal available
+BigDecimal requested
+Currency currency
}
class ValidationException {
+List~String~ violations
}
class AuthenticationException {
+String userId
}
class AuthorizationException {
+String userId
+String resource
}
ApplicationException --|> Exception
InsufficientFundsException --|> ApplicationException
ValidationException --|> ApplicationException
AuthenticationException --|> ApplicationException
AuthorizationException --|> ApplicationException
Checked and unchecked are Java language categories. RuntimeException and its subclasses, along with Error types, are unchecked; other exception types are checked. The compiler requires checked exceptions to be caught or declared. This classification does not determine whether a failure is recoverable or a programming bug. Choose the type based on the API contract and whether callers should have to handle or declare the failure. See JLS §11, Exceptions.
Standard Pattern for Checked Custom Exceptions
public class OrderNotFoundException extends Exception {
private final String orderId;
public OrderNotFoundException(String orderId) {
super("Order not found: " + orderId);
this.orderId = orderId;
}
public String getOrderId() {
return orderId;
}
}
Standard Pattern for Unchecked Custom Exceptions
public class InvalidStateTransitionException extends RuntimeException {
private final String currentState;
private final String attemptedTransition;
public InvalidStateTransitionException(String currentState, String attemptedTransition) {
super(String.format("Cannot transition from %s via %s", currentState, attemptedTransition));
this.currentState = currentState;
this.attemptedTransition = attemptedTransition;
}
}
Detailed Implementation
With Cause Chaining
When you catch a low-level exception and re-throw it as a domain exception, pass the original as the cause to retain the chain for trusted application code and internal diagnostics. The wrapper’s message should describe the domain failure; the cause carries the lower-level failure. A public API handler should map the domain exception to a safe response rather than serializing the cause, message, or stack trace.
Use this pattern when you catch a technical exception such as IOException or SQLException and translate it into a domain failure. The wrapper describes the failure at your abstraction level; the cause retains the lower-level detail for trusted diagnostics. A public API handler should map the domain exception to a safe response.
public class DataProcessingException extends Exception {
private final String operation;
public DataProcessingException(String operation, Throwable cause) {
super("Data processing failed during: " + operation, cause);
this.operation = operation;
}
public String getOperation() {
return operation;
}
}
// Usage
try {
processData();
} catch (IOException e) {
throw new DataProcessingException("import", e);
}
With Error Codes
Sometimes several failure modes belong to the same exception category, but creating a separate exception type for each scatters error handling across too many catch blocks. Error codes solve this by packing failure identifiers into a single exception class. Callers inspect the code to determine the exact failure without catching multiple types.
This fits when callers can catch one exception type but still need to distinguish the failure. A payment might fail because of insufficient funds, an expired card, or an invalid CVV. A PaymentException can carry a stable code for the failure category. Keep that machine-readable code separate from the human message: clients can branch on the code, while the message can be localized and phrased for people.
import java.math.BigDecimal;
import java.util.Currency;
public class PaymentException extends Exception {
private static final long serialVersionUID = 1L;
public enum ErrorCode {
INSUFFICIENT_FUNDS("PAYMENT_INSUFFICIENT_FUNDS", "payment.insufficient_funds"),
CARD_EXPIRED("PAYMENT_CARD_EXPIRED", "payment.card_expired"),
INVALID_CVV("PAYMENT_INVALID_CVV", "payment.invalid_cvv"),
PROCESSING_ERROR("PAYMENT_PROCESSING_ERROR", "payment.processing_error");
private final String publicCode;
private final String messageKey;
ErrorCode(String publicCode, String messageKey) {
this.publicCode = publicCode;
this.messageKey = messageKey;
}
public String getPublicCode() { return publicCode; }
public String getMessageKey() { return messageKey; }
}
private final ErrorCode code;
private final BigDecimal amount;
private final Currency currency;
public PaymentException(
ErrorCode code, BigDecimal amount, Currency currency, Throwable cause) {
super("Payment processing failed", cause);
this.code = code;
this.amount = amount;
this.currency = currency;
}
public ErrorCode getCode() {
return code;
}
public BigDecimal getAmount() { return amount; }
public Currency getCurrency() { return currency; }
}
Map Exceptions at the API Boundary
Keep the cause chain available to trusted application code and internal diagnostics. Do not serialize getMessage(), getCause(), or a stack trace into a public response; those details can reveal implementation information. Instead, map the exception to a documented code and a safe message selected for the request locale. The code is stable for client logic; the message is localized display text and may change.
import java.util.Locale;
import java.util.ResourceBundle;
public final class ApiErrorMapper {
public static ApiErrorResponse toResponse(PaymentException exception, Locale locale) {
PaymentException.ErrorCode code = exception.getCode();
ResourceBundle messages = ResourceBundle.getBundle("PaymentMessages", locale);
return new ApiErrorResponse(
code.getPublicCode(),
messages.getString(code.getMessageKey()));
}
}
final class ApiErrorResponse {
private final String code;
private final String message;
ApiErrorResponse(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() { return code; }
public String getMessage() { return message; }
}
For example, PaymentMessages.properties can define payment.insufficient_funds=The payment could not be completed. and PaymentMessages_fr.properties can provide the French text for the same key. Pass the user’s selected locale to ResourceBundle.getBundle; its Java SE 27 API documentation describes locale-specific bundles. The cause-preserving (String, Throwable) constructor is documented in the Java SE 27 Throwable API.
Failure Scenarios
// Scenario 1: Throwing wrong exception type
public void withdraw(BigDecimal amount) {
if (amount.compareTo(balance) > 0) {
throw new RuntimeException("Insufficient funds"); // Too generic
// Better: throw new InsufficientFundsException(balance, amount, currency);
}
}
// Scenario 2: Losing original cause
try {
process();
} catch (IOException e) {
throw new CustomException("Process failed"); // Cause lost!
// Better: throw new CustomException("Process failed", e);
}
// Scenario 3: Non-serializable exception in distributed systems
public class BadException extends Exception { // Missing serialVersionUID
// If this crosses JVM boundaries, serialization may fail
}
Trade-off Table
| Approach | Pros | Cons |
|---|---|---|
| extends Exception | Compiler enforces handling | Verbose for callers |
| extends RuntimeException | No declaration needed | Easy to forget to handle |
| Exception with error codes | Structured error info | More boilerplate |
| RuntimeException with codes | Flexible, structured | Not enforced by compiler |
Best Practices
- Name exceptions descriptively — End with “Exception”:
OrderNotFoundException - Add useful context — Include a cause, code, or domain data when callers need it
- Keep diagnostics private — Avoid placing sensitive values in messages or
toString()output that may reach clients - Consider serialization — Add
private static final long serialVersionUIDif crossing JVM boundaries - Document with Javadoc — Explain when this exception is thrown and how to handle it
/**
* Thrown when a requested domain entity cannot be found.
*
* <p>This exception indicates a logical error in the application rather
* than a system failure. Callers should typically return 404 responses
* or prompt for entity re-creation.</p>
*/
public class EntityNotFoundException extends Exception {
private final String entityType;
private final Object entityId;
public EntityNotFoundException(String entityType, Object entityId) {
super(String.format("%s with id '%s' not found", entityType, entityId));
this.entityType = entityType;
this.entityId = entityId;
}
}
Security Notes
- Do not expose internal IDs or paths — Exception messages may be logged and exposed to clients
- Sanitize user input in exceptions — If the exception message includes user-provided data, sanitize it
- Preserve causes internally, hide details from clients — Keep the cause chain for diagnostics and map exceptions to a stable code and localized safe message at the API boundary
- Be careful with serialization — Exception data that crosses JVM boundaries becomes attack surface
Common Pitfalls
- Creating shallow subclasses — Empty
extends Exceptionadds no value - Dropping the cause — When wrapping an exception, pass the original as the cause to preserve context
- Choose checked or unchecked by API contract — Checked types require catch-or-declare; unchecked types do not
- Over-specific exceptions — Too many exception types make error handling verbose
- Missing serialVersionUID — Serializable exceptions may fail when crossing JVM boundaries
Quick Recap
- Custom exceptions should have clear names and include context callers need
- Use a checked type when callers should be required to catch or declare the failure
- Use an unchecked type when that compile-time requirement would not help the caller; either category can represent a domain failure
- Preserve the cause when translating a lower-level failure
- Avoid including sensitive values in exception messages or diagnostic text that could reach clients
- Document when to throw and how to handle in Javadoc
Interview Questions
Further Reading
- Throwable Hierarchy — exception and error class hierarchy in Java
- Try-Catch-Finally — basic exception handling syntax
- Throw and Throws — throwing and declaring exceptions
- Try With Resources — automatic resource cleanup with AutoCloseable
- Exception Best Practices — when and how to use exceptions effectively
Conclusion
Use a custom exception when a built-in type does not give callers enough information to handle a domain failure. Checked and unchecked describe compile-time handling rules: checked exceptions must be caught or declared, while RuntimeException types do not. That choice depends on the API contract, not a rule that checked failures are recoverable and unchecked failures are bugs. Add context or a stable error code only when callers need it.
The Throwable Hierarchy explains how exception types fit into Java’s class hierarchy. When wrapping a lower-level failure, preserve its cause for internal diagnostics. At a public API boundary, return a stable code and a localized safe message, and document the conditions callers need to handle.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.