Custom Exceptions
A custom exception gives a domain rule a name that the rest of the application can understand. RuntimeException says only that execution failed at runtime; UserNotFoundException says what the service could not find. This distinction lets a global handler choose a stable HTTP status without inspecting arbitrary message text.
Designing the hierarchy
Create a custom exception when callers need to react differently to a particular business failure. A small application may have one base BusinessException and more specific types below it. Keep the hierarchy shallow. Inheritance should represent a meaningful handling relationship, not every possible noun in the domain.
public class BusinessException extends RuntimeException {
public BusinessException(String message) {
super(message);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
}
public final class UserNotFoundException extends BusinessException {
public UserNotFoundException(long userId) {
super("User not found: " + userId);
}
}
Use a constructor for structured inputs instead of forcing every caller to build a message. The cause constructor is for wrapping a lower-level failure, such as a database or file exception. Do not expose internal SQL, credentials, or stack traces through the public message.
A service boundary
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
public User findUser(long id) {
if (id <= 0) {
throw new ValidationException("id must be positive");
}
return repository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
}
The service owns the rule because it knows what “user not found” means for the use case. The controller does not need to inspect Optional or compare strings. Later, @RestControllerAdvice can map UserNotFoundException to 404 and ValidationException to 400.
| Exception | Meaning | Typical API status |
|---|---|---|
UserNotFoundException |
Requested user does not exist | 404 Not Found |
ResourceNotFoundException |
Requested domain resource does not exist | 404 Not Found |
ValidationException |
Input violates a business or request rule | 400 Bad Request |
BusinessException |
Known business operation cannot continue | Depends on subtype |
Do not create an exception for every ordinary branch. “No search results” may be a valid empty list. Do create one when the caller must distinguish the situation from success. Name the type after the failed business meaning, keep messages safe, and preserve causes when translating infrastructure failures.
Glossary
- bytecode
- Platform-independent compiled code that the JVM can execute.
- class
- A blueprint that defines fields and methods for objects in object-oriented programming.
- object
- A runtime instance of a class with its own state and behavior.
- method
- A named block of behavior that belongs to a class or object and can be called by code.
- field
- A variable stored inside a class or object that represents part of its state.
- constructor
- A special method-like block used to create and initialize a new object.
- package
- A namespace that groups related Java classes and helps organize code.
- interface
- A contract that defines methods a class can implement without prescribing all internal details.
- generics
- A language feature that lets code work with types as parameters while preserving type safety.
- type erasure
- The Java compiler process that removes most generic type details from runtime bytecode.
- collection
- A data structure that stores a group of elements and provides operations over them.
- list
- An ordered collection where elements have positions and duplicates are allowed.
- set
- A collection that stores unique elements and is commonly used for membership checks.
- map
- A key-value data structure where each key points to a value.
- queue
- A collection designed for processing elements in a defined order, often first-in-first-out.
- lambda
- A compact function-like expression used to pass behavior as data.
- functional interface
- An interface with one abstract method, suitable for lambdas and method references.
- stream
- A Java API for processing data sequences with operations such as map, filter, and reduce.
- optional
- A container object that represents a value that may or may not be present.
- thread
- An independent path of execution inside a running program.
- synchronization
- Coordination that protects shared data when multiple threads access it.
- heap
- The runtime memory area where Java objects are allocated.
- stack
- The runtime memory area that stores method calls, local variables, and call frames.
- garbage collector
- A JVM component that automatically frees memory occupied by objects no longer reachable.
- memory leak
- A situation where memory remains occupied because objects are still referenced but no longer useful.