Exception Best Practices: Patterns and Anti-Patterns in Java
Learn Java's checked and unchecked exception rules, preserve causes when wrapping, log failures once at the handling boundary, and return safe API errors.
Learn how Java classifies checked and unchecked exceptions, when to propagate or wrap failures, and where to log them. Examples show how an API can return a stable error code and safe message without exposing exception details.
Exception Best Practices: Patterns and Anti-Patterns in Java
Exception handling determines whether a failure is recovered, retried, or reaches a useful diagnostic. A vague catch can hide a failure; an exception sent directly to a client can expose internal details. The examples here focus on where to catch, wrap, log, and respond.
Introduction
An exception type does not, by itself, say whether an application can recover. The JLS classifies exceptions as checked or unchecked by their place in the type hierarchy and whether compile-time checking applies. RuntimeException and Error subclasses are unchecked; other exception classes are checked. A RuntimeException is often used for programming mistakes, but it can also represent invalid input or a domain failure. Whether a caller should recover is a separate API design decision. See JLS SE 27, Chapter 11.
When a lower layer adds context, it should preserve the original cause and let the failure propagate. The layer that decides how to recover or answer the request can log it once:
try {
processOrder(orderId);
} catch (SQLException e) {
throw new OrderProcessingException("Could not process order", e);
}
This keeps the database exception available as the cause without logging it at a layer that cannot handle the request. A boundary handler can record the failure and return a sanitized response, as shown below.
When to Use
Apply these patterns when:
- Writing application error handling that needs to be debugged
- Designing APIs that will be consumed by other teams
- Building libraries or shared components
- Implementing logging and observability
- Handling cross-boundary failures (I/O, network, database)
When NOT to Use
- Do not apply patterns mechanically: Context matters; a pattern that works in one layer may be wrong in another
- Do not over-engineer for simple utilities: A private helper method does not need the full treatment
- Do not log in a layer that only translates and rethrows: Log once where recovery or the external response is decided
Exception Handling Anti-Patterns
flowchart TD
A["Anti-Patterns"] --> B["Swallowed Exception"]
A --> C["Generic Catch"]
A --> D["Return in Finally"]
A --> E["Lost Cause"]
A --> F["Exposed Stack Trace"]
B --> B1["Empty catch or System.out.println"]
C --> C1["catch (Exception e) {}"]
D --> D1["return in finally block"]
E --> E1["throw new Exception(msg) without cause"]
F --> F1["e.printStackTrace() in production"]
Anti-Pattern 1: Swallowed Exceptions
An empty catch block makes the operation look successful even though it failed. Later code may receive incomplete data or leave state inconsistent, and the original failure is no longer available to diagnose. Catch an exception only when this layer can recover, translate, or report it to the caller.
// BAD: Silent failure hides bugs
try {
sendEmail();
} catch (Exception e) {
// Do nothing: email failure goes unnoticed
}
// BAD: Comment-only handling
try {
processOrder();
} catch (OrderException e) {
// TODO: handle this
}
// GOOD: Log and either recover or propagate
try {
sendEmail();
} catch (MailException e) {
logger.error("Failed to send email for order {}", orderId, e);
notificationService.notifyAdmins(orderId, "email failed");
}
Anti-Pattern 2: Generic Catch
catch (Exception e) catches checked exceptions and unchecked exceptions that extend RuntimeException. The unchecked classification means the compiler does not require a catch or throws declaration; it does not mean the exception is always a programming bug or unrecoverable. For example, an application may use an unchecked exception for invalid input or a domain rule. Prefer specific catches where the code can take a specific action. At an outer boundary, a broad Exception catch can provide a final sanitized fallback for unexpected failures. Avoid catching Throwable in ordinary application code because it also catches Error subclasses such as OutOfMemoryError.
// BAD: Too broad for code that only needs to handle a validation failure
try {
riskyOperation();
} catch (Exception e) {
System.out.println("Something went wrong"); // Too generic
}
// BAD: Catching Throwable catches Errors
try {
riskyOperation();
} catch (Throwable t) {
// Also catches Error subclasses such as OutOfMemoryError.
}
// GOOD: Catch specific types
try {
riskyOperation();
} catch (ValidationException e) {
handleValidationFailure(e);
} catch (ProcessingException e) {
handleProcessingFailure(e);
}
Anti-Pattern 3: Lost Exception Cause
When translating a low-level exception, pass it as the cause. The caller can then inspect the original failure without forcing every layer to depend on the lower layer’s exception type. If the current layer cannot handle the failure, wrap or propagate it without logging; log once at the layer that owns recovery or the response.
// BAD: Cause is lost
try {
parseData();
} catch (IOException e) {
throw new DataException("Parsing failed"); // Original cause lost
}
// GOOD: Preserve cause chain
try {
parseData();
} catch (IOException e) {
throw new DataException("Parsing failed", e); // Cause preserved
}
Best Practice Patterns
Pattern 1: Meaningful Exception Messages
// BAD: No context, no actionable information
throw new Exception("Error");
// BAD: Technical detail exposed to users
throw new SQLException("Connection refused: host=db.example.com, port=5432, user=admin");
// GOOD: Context-aware message
throw new OrderNotFoundException(
String.format("Order '%s' not found for customer '%s'", orderId, customerId)
);
Exception messages should help diagnose a failure without carrying secrets or unnecessary personal data. A message such as “Order not found” may be enough; add an approved identifier to internal logs when it helps correlate the event. Never send exception messages, causes, or stack traces directly to API clients.
Keep the message focused on the failed operation. Do not copy raw request values into logs or exception text without validation and redaction; user-controlled text can forge log entries or expose sensitive data.
Pattern 2: Chaining and Wrapping
// Translate the storage failure and preserve its cause. This layer does not log it.
try {
connection.setAutoCommit(false);
processPayment();
connection.commit();
} catch (SQLException e) {
try {
connection.rollback();
} catch (SQLException rollbackFailure) {
e.addSuppressed(rollbackFailure);
}
throw new PaymentProcessingException(
"Payment processing failed",
e
);
}
When an exception is translated, keep the original as the cause. Use the new exception’s message to describe the operation at this layer; do not copy sensitive data from the lower-level message. The Exception(String message, Throwable cause) constructor preserves the cause chain.
The cause chain records how a failure crossed layers. For example, a data-access exception can wrap an SQLException, whose cause may be a SocketException. A rollback failure can be attached with addSuppressed() so it does not replace the original failure.
Try-with-resources keeps the primary exception and attaches a failure from close() as a suppressed exception. Call getSuppressed() to inspect those additional failures; they do not replace the primary exception.
Pattern 3: Fail-Fast Validation
// Validate early, fail fast
public void transferFunds(Account from, Account to, BigDecimal amount) {
if (from == null) {
throw new IllegalArgumentException("Source account cannot be null");
}
if (to == null) {
throw new IllegalArgumentException("Target account cannot be null");
}
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
throw new IllegalArgumentException("Transfer amount must be positive");
}
if (from.equals(to)) {
throw new IllegalArgumentException("Cannot transfer to same account");
}
// Proceed with business logic
}
Validate arguments and preconditions before changing state. Keep each check close to the operation it protects, whether that is a public method or a helper that owns the invariant. A clear failure at the boundary is easier to diagnose than a later null dereference.
IllegalArgumentException is an unchecked exception commonly used when a method receives an invalid argument. The JLS category says the compiler does not require callers to catch or declare it; it does not determine whether a failure is recoverable. A domain validation failure can also use an unchecked type or a checked domain exception, depending on the API contract and caller needs.
Checking preconditions before updating state avoids some partial failures, but it does not make a multi-step transfer atomic. Use a transaction or suitable locking when all account updates must succeed or fail together. Keep each invariant close to the operation that enforces it.
Pattern 4: Exception Translation in Service Boundaries
// DAO layer: low-level exceptions
try {
accountRepository.save(account);
} catch (SQLException e) {
throw new DataAccessException("Failed to save account", e);
}
// Service layer: domain exceptions
try {
accountRepository.save(account);
} catch (DataAccessException e) {
throw new AccountManagementException(
"Unable to create account",
e
);
}
// Controller layer owns the HTTP response and logs this failure once.
try {
accountService.create(request);
} catch (AccountManagementException e) {
String requestId = requestContext.requestId();
logger.error("Account request failed requestId={}", requestId, e);
return Response.status(500).entity(
new ErrorResponse(
"ACCOUNT_REQUEST_FAILED",
"The request could not be completed.",
requestId
)
).build();
}
Each layer can add its own vocabulary while preserving the cause. The data-access layer handles SQL failures; the service layer describes account operations; the controller maps known failures to HTTP status and response codes. The lower layers do not log while translating and rethrowing. The controller owns this response, so it records the failure once.
For an unexpected failure, the same boundary can provide a generic fallback code. Known domain failures can map to their own stable codes and safe messages. Never build the response from e.getMessage(), e.getCause(), or a stack trace. Configure logs to redact secrets and personal data that might appear in exception messages.
Failure Scenarios
| Failure | Internal handling | Client response |
|---|---|---|
| A storage exception is translated by a service | Wrap it with the original cause; do not log while propagating | The response boundary logs once and returns a stable code with a safe message |
| A known validation or domain rule fails | Use an exception type that fits the API contract; checkedness does not determine recoverability | Map it to an appropriate status, stable code, and client-safe message |
| An unexpected exception reaches the HTTP boundary | Redact sensitive fields, then record the exception once with a request ID | Do not include the exception message, cause, stack trace, token, or internal details |
// Scenario 1: Exception masking in lambda
List<String> result = strings.stream()
.map(s -> {
try {
return parse(s);
} catch (ParseException e) {
return null; // Masks failure
}
})
.collect(Collectors.toList());
// Scenario 2: Exception lost in executor
Future<?> future = executor.submit(() -> {
throw new RuntimeException("task failed");
});
try {
future.get();
} catch (ExecutionException e) {
// This handler owns the task failure; log it once here.
logger.error("Task failed", e);
}
// Scenario 3: Swallowed in thread pool
executor.execute(() -> {
try {
process();
} catch (Exception e) {
// Swallowed: main thread never knows
}
});
Trade-off Table
| Practice | When to Use | When to Avoid |
|---|---|---|
| Catch specific exceptions | This layer can take a type-specific action | Catching unrelated failures without a plan |
| Log a handled failure once | This layer owns recovery or the external response | A lower layer that only propagates or wraps it |
| Wrap with context and cause | Translating across a service boundary | Rewrapping within the same layer without context |
| Fail-fast validation | Rejecting invalid input before changing state | Using exceptions for routine control flow |
| Inspect suppressed exceptions | Multiple operations or resources fail | Treating a suppressed failure as the primary one |
Observability Checklist
- Handled failures are logged once at the layer that owns recovery or the response
- Lower layers propagate or wrap failures with the original cause and do not log before rethrowing
- Logs include an approved correlation identifier and redact tokens, credentials, and sensitive input
- No empty catch blocks or swallowed exceptions
- API responses contain a stable error code and safe message, never exception text, causes, or stack traces
- Suppressed exceptions retrieved in multi-resource operations
- Internal details are available only in access-controlled server logs
Security Notes
- Return safe API errors: Use a stable machine-readable code and a message written for clients; omit exception messages, causes, stack traces, tokens, and internal details
- Log at the response boundary: Preserve causes while propagating through lower layers, then log once where the failure is handled
- Redact before logging: Exception messages can contain credentials, tokens, personal data, or user-controlled text
- Be careful with exception types in security decisions: Type of exception should not grant unauthorized access
// The HTTP boundary owns the response and logs the failure once.
try {
processUserData(userId);
} catch (Exception e) {
String requestId = requestContext.requestId();
logger.error("Request failed requestId={}", requestId, e);
return Response.status(500).entity(
new ErrorResponse(
"REQUEST_FAILED",
"The request could not be completed.",
requestId
)
).build();
}
Apply redaction in the logging pipeline before recording exception details. For expected domain failures, map each case to an appropriate HTTP status and stable code; keep the client message separate from Throwable.getMessage(). The logger used in the example must redact sensitive values before writing exception details.
Common Pitfalls / Anti-Patterns
- Ignoring a failure without recovery: A catch block should recover, translate, or propagate the failure
- Catching generic Exception or Throwable: Catch a broad exception only at an outer boundary that can provide a safe fallback; do not catch
Throwablein ordinary application code - Returning from finally: Suppresses exceptions from try blocks
- Exception in finally overwriting original: Use suppressed exceptions properly
- Exposing internal details in messages: File paths, SQL structure, class names help attackers
- Not preserving cause when wrapping: The lower-level reason is lost
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
- Custom Exceptions: creating application-specific exception types
- JLS SE 27, Chapter 11: Exceptions: exception classes and compile-time checking
- OWASP REST Security Cheat Sheet: safe error responses
- OWASP Logging Cheat Sheet: protecting log data
- Oracle Java Tutorials: Exceptions: Java exception handling basics
- Effective Java: Item 75: Include cause in exception detail messages: exception chaining
Conclusion
Choose checked or unchecked exception types according to the API contract and Java’s compile-time rules; the type does not tell callers whether recovery is possible. Catch a specific failure when the code can act on it. When translating an exception, preserve its cause and let lower layers propagate without logging if they cannot handle it. Log once at the layer that owns recovery or the external response, after redacting sensitive data.
Quick reference for your next codebase audit:
- Catch the type your code can handle; do not blanket-catch
RuntimeExceptionjust because it is unchecked - Preserve the original cause when translating:
throw new DomainException(msg, e) - Keep API messages separate from diagnostics; include only approved, redacted context in logs
- Log once where recovery or the response is decided; lower layers should propagate or wrap without logging
- Validate at the method entrance; throw before any state changes
These patterns build on the fundamentals of Throwable Hierarchy (which exceptions to catch) and Try-Catch-Finally (how cleanup works). For modern resource management, Try-With-Resources eliminates cleanup boilerplate, and for domain-specific errors, Custom Exceptions say more about your intent than generic types.
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.