"@ExceptionHandler"

@ExceptionHandler connects an exception type with a method that creates a response. The annotation can be placed in a controller for local behavior or in advice for shared behavior. It is a mapping mechanism, not a replacement for domain design: the service still throws a meaningful exception, and the handler translates it at the web boundary.

Spring MVC exception flow

A local handler

@ExceptionHandler(UserNotFoundException.class)
ResponseEntity<ErrorResponse> userNotFound(
        UserNotFoundException ex,
        HttpServletRequest request) {
    var body = new ErrorResponse(
        "USER_NOT_FOUND", ex.getMessage(), request.getRequestURI());
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(body);
}

Spring selects this method when the controller invocation throws UserNotFoundException. The exception parameter gives access to the safe message; the request gives context such as the path. Returning ResponseEntity makes the status and body explicit. A handler may also return a DTO directly when a separate response status annotation is used.

Handlers should be specific. A method for UserNotFoundException should not also decide how validation, authentication, and database failures are represented. Define one response shape and stable error codes so clients do not need to parse English or Russian messages.

Handler choice When it is appropriate
controller-local @ExceptionHandler Only one controller owns the rule
advice handler Several controllers share the response
specific exception parameter One known mapping and status
broad Exception handler Last safety net with generic 500

Ordering and fallback

Spring resolves the most specific compatible handler. Do not create overlapping methods casually; a broad Exception handler can become a confusing fallback if it performs business decisions. Use a final handler to log an unexpected failure and return a generic safe response. Never include ex.getStackTrace() in that response.

A validation handler is often separate from a domain handler. MethodArgumentNotValidException contains field errors; convert them into a predictable list rather than returning framework internals. A missing user and invalid request are different failures even if both originate during one HTTP call.

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.