Spring MVC differentiates between exception types by matching the thrown exception's class against methods annotated @ExceptionHandler, each of which declares which exception type it's responsible for handling.
A controller might have separate @ExceptionHandler methods for UserNotFoundException, returning a 404 with a JSON error body, and for generic IllegalArgumentException, returning a 400 — Spring picks whichever matches the exception actually thrown.
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleNotFound(UserNotFoundException ex) {
return ResponseEntity.status(404).body(ex.getMessage());
}A concise interview answer is
Spring matches a thrown exception's type against @ExceptionHandler method declarations, preferring the most specific match available, and walking up the class hierarchy if there's no exact match. Those handlers can be local to a controller or centralized in a @ControllerAdvice class for app-wide exception handling.
Last updated: 16 July 2026
Previous question: What is the use of @ExceptionHandler?
Next question: What are the options for implementing security in a Spring MVC application?