Clean • Professional
@ExceptionHandler (Controller-Level Exception Handling)@ExceptionHandler is a Spring annotation used to handle exceptions at the controller level. Instead of letting an application crash or return generic error responses, it allows you to catch exceptions and return meaningful, structured messages to clients.
It is especially useful in REST APIs for providing clean and consistent error responses.
@ExceptionHandler?@ExceptionHandler is a controller-level exception handler in Spring Boot:
Simple Definition:
A Spring annotation used to handle exceptions thrown by controller methods without using try-catch blocks.
Basic Example
@RestController
@RequestMapping("/users")
publicclassUserController {
@GetMapping("/{id}")
public UsergetUser(@PathVariableint id) {
return userService.findById(id);// may throw UserNotFoundException
}
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String>handleUserNotFound(UserNotFoundException ex) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
}
Outcome:
@ExceptionHandler?Benefits of using @ExceptionHandler:
@ExceptionHandler Works@ExceptionHandler method within the same controllerFlow Diagram:
User Request → ControllerMethod Executes
↓
UserNotFoundException Thrown?
↓
Yes → @ExceptionHandler CapturesException
↓
Return Custom Response (e.g.,404NotFound)You can handle more than one exception in a single handler:
@ExceptionHandler({UserNotFoundException.class, OrderNotFoundException.class})
public ResponseEntity<String>handleNotFoundExceptions(RuntimeException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
REST APIs work better with structured JSON errors instead of plain text:
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<ErrorResponse>handleUserNotFound(UserNotFoundException ex) {
ErrorResponseerror=newErrorResponse(
ex.getMessage(),
HttpStatus.NOT_FOUND.value(),
System.currentTimeMillis()
);
returnnewResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
ErrorResponse Class:
publicclassErrorResponse {
private String message;
privateint status;
privatelong timestamp;
publicErrorResponse(String message, int status,long timestamp) {
this.message = message;
this.status = status;
this.timestamp = timestamp;
}
// getters and setters
}
Example JSON Response:
{
"message":"User not found",
"status":404,
"timestamp":1672567890123
}
@ExceptionHandler in Spring Boot@ExceptionHandler works at the controller level, which means it only handles exceptions inside the controller where it is defined.
| Feature | Description |
|---|---|
| Scope | Only works within the controller it is defined in |
| Reusability | Low – cannot be reused across multiple controllers |
| Best For | Small applications or single-controller APIs |
| Production Use | Limited – not ideal for large or microservice-based projects |
For global exception handling, use @ControllerAdvice or @RestControllerAdvice
@ExceptionHandler vs Try-CatchWhen handling exceptions in Spring Boot, you can use Try-Catch or @ExceptionHandler.
Understanding the differences helps you choose the right approach for your project.
| Feature | Try-Catch | @ExceptionHandler |
|---|---|---|
| Code Cleanliness | Messy – try-catch blocks in every method clutter your code | Cleaner – separates business logic from error handling |
| Reusability | None – logic has to be repeated in each method | Limited – works per controller, can handle multiple exceptions in one method |
| Maintainability | Hard – changes require editing every method | Easier – handler method can be updated once for the controller |
| Recommended For | No – not ideal for REST APIs or large projects | Yes – small or single-controller applications |
@ExceptionHandler@ExceptionHandler is a controller-level exception handling approach, which means it works only within the controller where it is defined.
Knowing when to use it ensures clean, maintainable, and professional REST APIs.
Best Use Cases:
Use @ExceptionHandler when:
Example: A small user management API with just one UserController.
Avoid Using @ExceptionHandler When
Do not rely on @ExceptionHandler if:
In these cases, prefer @RestControllerAdvice or @ControllerAdvice, which provide global and reusable exception handling.
@ExceptionHandler is a controller-level exception handling solution in Spring Boot:
Limitations: Works only for single controllers. For large applications, use:
@ControllerAdvice → Global exception handling for all controllers@RestControllerAdvice → REST-friendly global exception handling