Lesson 12 of 12 · 9 min · Exceptions
Custom exceptions and handling errors in layers
What you will learn
- When to create a custom exception and how to write one
- Wrap low-level exceptions without losing the cause
- Where to throw, translate, handle and log in a layered application
- Design errors that clients of a REST API can understand
- Common anti-patterns in exception handling
In simple words
A real application has layers, like a restaurant: the kitchen (database), the waiter (business logic) and the menu the customer sees (the web API). If the kitchen runs out of eggs, the waiter should not hand the customer a raw "egg shortage in the freezer, shelf 3" note. The waiter turns it into a polite message. Exception handling in layers works the same way: each layer turns low-level problems into messages that make sense for the layer above.
Words to know
- Custom exception: an exception class you write for a specific problem in your domain.
- Exception translation: catching a low-level exception and throwing a higher-level one.
- Root cause: the original exception behind a chain of wrapped ones.
- Layer: a part of the application with one role, such as controller, service or repository.
Why custom exceptions
Standard exceptions are good for general mistakes (IllegalArgumentException). Create your own when the problem is part of your domain and callers need to handle it specifically:
OrderNotFoundException: map it to an HTTP 404.InsufficientStockException: show "only 3 left".PaymentFailedException: offer another method.
A name that says what happened is more helpful than Exception("error").
Writing one
public class OrderNotFoundException extends RuntimeException {
private final int orderId;
public OrderNotFoundException(int orderId) {
super("Order " + orderId + " was not found");
this.orderId = orderId;
}
public int orderId() { return orderId; }
}
public class PaymentFailedException extends RuntimeException {
public PaymentFailedException(String message, Throwable cause) {
super(message, cause); // always keep the cause
}
}
Guidelines:
- Extend
RuntimeException(unchecked) for most application errors; use a checked exception only when callers must be forced to recover and can. - Provide constructors that take a message and a cause.
- Carry useful data (ids, field names) in fields, not only in the text.
- End the class name with Exception.
- A small hierarchy can help:
abstract class ShopException extends RuntimeException, with subclasses for each case, so onecatch (ShopException e)can handle all of them in one place. - Do not create an exception for every if statement; reuse standard ones when they fit.
- Add
serialVersionUIDonly if you serialise exceptions (rarely).
Wrapping and keeping the cause
When a low-level exception crosses a layer boundary, wrap it in one that the next layer understands, and keep the original as the cause:
public Order load(int id) {
try {
return jdbc.queryForObject(SQL, mapper, id);
} catch (EmptyResultDataAccessException e) {
throw new OrderNotFoundException(id); // a "not found" is expected: no cause needed
} catch (DataAccessException e) {
throw new RepositoryException("could not load order " + id, e); // keep the cause
}
}
This is exception translation. The reasons are encapsulation (the service layer should not depend on java.sql.SQLException or on JPA types) and meaning (callers handle a domain error, not a driver error). The stack trace of the final exception shows Caused by: ... with the original, so nothing is lost.
Handling in layers
A typical web application has three layers; each has a clear job for errors:
| Layer | Job | Errors |
|---|---|---|
| Repository (data access) | talk to the database | translate technical exceptions into data-access or "not found" exceptions; do not log and swallow |
| Service (business logic) | apply the rules | throw domain exceptions (InsufficientStockException); decide whether to retry or compensate; keep transactions in mind (a runtime exception rolls back a Spring transaction) |
| Controller (API) | translate to the client | convert exceptions to HTTP status codes and a consistent error body; never leak stack traces or SQL |
A good rule: throw early, catch late. Detect the problem where you have the facts, let it travel up unchanged, and handle it where you can do something sensible: show a message, retry, or return an HTTP error. Do not catch an exception in the middle just to log it and carry on with bad data.
Log once: log an exception where you finally handle it, not at every layer it passes through. Otherwise one failure fills the logs with five copies of the same stack trace. Include context (order id, user id) but never log secrets such as passwords, card numbers or tokens.
A central handler for REST APIs
Instead of try/catch in every controller, one place maps exceptions to responses. In Spring, @RestControllerAdvice with @ExceptionHandler does this:
@RestControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<ApiError> notFound(OrderNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ApiError("ORDER_NOT_FOUND", e.getMessage()));
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<ApiError> badRequest(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(new ApiError("BAD_REQUEST", e.getMessage()));
}
@ExceptionHandler(Exception.class) // last resort
public ResponseEntity<ApiError> unexpected(Exception e) {
log.error("Unhandled error", e); // log the real cause once
return ResponseEntity.status(500).body(new ApiError("INTERNAL_ERROR", "Something went wrong"));
}
}
public record ApiError(String code, String message) {}
The Spring Boot course covers this in detail (including ProblemDetail, the standard error format for HTTP APIs). The ideas are general: a stable error code that clients can program against, a human-readable message without internals, and the right HTTP status (400 for client mistakes, 404 for missing items, 409 for conflicts, 500 for our own bugs).
Retry, fallback and compensation
Some failures are temporary (a network blip). The service layer may retry a few times with a delay, use a fallback value, or compensate (refund a payment when the order could not be created). Do these deliberately, with limits, and only for errors that make sense to retry. Idempotent operations are safe to retry; non-idempotent ones (charging a card) need care.
Anti-patterns
- Swallowing:
catch (Exception e) { }. - Log and throw: logging the exception and then rethrowing it, so it is logged again further up.
- Throwing
ExceptionorRuntimeExceptiondirectly with no meaning. - Losing the cause:
throw new X(e.getMessage()). - Returning
nullor an error code instead of throwing when something fails. - Catching
Exceptionin the service layer to hide failures from the controller. - Exposing internals (SQL, class names, stack traces) in API responses.
- Using exceptions for control flow in normal, frequent cases.
- Mixing checked exceptions through many layers, forcing
throwseverywhere.
Try it yourself
- Create
OrderNotFoundExceptionandInsufficientStockExceptionextending a baseShopException. - Write a repository method that translates a low-level exception into your exception with the cause.
- Print the stack trace of a wrapped exception and find the root cause line.
- Write a handler (a method or a class) that maps each exception to an HTTP status code and a message.
- Find a place in code you have written that logs and rethrows, and fix it.
Check yourself
When should you create a custom exception?
When the error is meaningful in your domain and callers need to treat it specifically, such as mapping it to a particular HTTP status or recovery action.
Why keep the cause when wrapping an exception?
So the original exception and its stack trace remain visible as Caused by, which makes diagnosing the real problem possible.
What does "throw early, catch late" mean?
Detect and raise errors where the facts are known, and handle them at a higher level where you can respond sensibly.
Why should exceptions be logged only once?
Logging at every layer produces duplicate entries for one failure and makes logs noisy and hard to read.
Interview questions
How do you handle exceptions in a layered Spring application?
The repository translates data-access exceptions, the service throws domain exceptions and manages transactions, and a central @RestControllerAdvice maps exceptions to HTTP status codes and a consistent error body, logging unexpected errors once.
Should custom exceptions be checked or unchecked?
Usually unchecked, extending RuntimeException, because most callers cannot recover and forced throws clauses add clutter; use checked only where a caller can and must react.
What is exception translation and why use it?
Catching a low-level exception and throwing a higher-level one (with the cause), so upper layers do not depend on implementation details such as SQLException.
Summary
- Custom exceptions name domain problems; extend
RuntimeExceptionand always keep the cause. - Translate low-level exceptions at layer boundaries; throw early, catch late, log once.
- A central handler maps exceptions to HTTP responses with stable codes and safe messages.
- Avoid swallowing, log-and-throw, losing causes and leaking internals.
Going deeper
- The Java Tutorials: Exceptions: the base concepts.
- Throwable API documentation: causes, suppressed exceptions and stack traces.
- dev.java: Exceptions: custom exceptions and best practices.
- Spring Framework: Controller advice:
@ControllerAdviceand@ExceptionHandler.
See how much of this you can explain
A free mock interview asks you new questions on Core Java: OOP, collections and exceptions for Java Full Stack Developer and scores every answer, with what to fix.