What is the use of @ExceptionHandler?

@ExceptionHandler marks a method as the designated error handler for one or more exception types thrown during controller processing, letting you turn an exception into a controlled, meaningful HTTP response instead of a default error page.

Key Points

Example

A method throwing ItemNotFoundException when a lookup fails can be paired with an @ExceptionHandler(ItemNotFoundException.class) method that returns a 404 response with a clear JSON error message, instead of the client seeing a generic 500 error.

@ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<String> handleNotFound(ItemNotFoundException ex) {
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}

Interview Tip

A concise interview answer is

@ExceptionHandler lets me designate a method to catch a specific exception type thrown from a controller and turn it into a controlled response with the right status code and message, instead of letting it bubble up as a generic error. Putting it in a @ControllerAdvice class makes the handling apply globally across all controllers.

Last updated: 16 July 2026

Previous question: How can you configure a global exception handler using @ControllerAdvice?

Next question: How does Spring MVC differentiate between different types of exceptions?

More Spring MVC (Optional) interview questions

All Spring MVC (Optional) questions