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.
Key Points: • Each @ExceptionHandler method specifies one or more exception classes it handles, either via the annotation's value or the method parameter type. • When an exception propagates out of a controller method, Spring looks for the most specific matching handler, walking up the exception's class hierarchy if needed. • Handlers can live in the same controller (local scope) or in a class annotated @ControllerAdvice (global scope across all controllers). • If multiple handlers could match, Spring prefers the one with the most specific exception type over a broader superclass match. • The matched handler can return a custom response body, status code, or an error view, tailored to that specific exception type.
Example: 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.
Code Example:
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleNotFound(UserNotFoundException ex) {
return ResponseEntity.status(404).body(ex.getMessage());
}Interview Tip: 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."