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: • The annotated method's parameter type (or the annotation's value) declares which exception class it catches. • When that exception is thrown anywhere in the controller's methods, Spring routes it to the matching handler instead of propagating it further. • Handlers can return a custom response body, status code via @ResponseStatus or ResponseEntity, or a dedicated error view. • Declaring the handler in a class annotated @ControllerAdvice makes it apply globally across all controllers instead of just one. • Multiple handlers can coexist for different exception types, letting each error be reported with the appropriate detail and status code.

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.

Code Example:

@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."