@ExceptionHandler helps you catch and handle errors in your web app controllers so users see friendly messages instead of crashes.
@ExceptionHandler in controllers in Spring Boot
@ExceptionHandler(ExceptionType.class)
public ResponseEntity<String> handleException(ExceptionType ex) {
// handle error
}Place this method inside your controller class or a @ControllerAdvice class.
The method catches exceptions of the specified type thrown in controller methods.
@ExceptionHandler(NullPointerException.class) public ResponseEntity<String> handleNullPointer(NullPointerException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Null value found!"); }
@ExceptionHandler(Exception.class) public ResponseEntity<String> handleAllExceptions(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Something went wrong."); }
This controller has a /divide endpoint that causes a divide-by-zero error. The @ExceptionHandler catches that error and returns a 400 status with a friendly message.
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @GetMapping("/divide") public int divide() { int a = 10; int b = 0; return a / b; // will cause ArithmeticException } @ExceptionHandler(ArithmeticException.class) public ResponseEntity<String> handleArithmeticException(ArithmeticException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Cannot divide by zero."); } }
You can have multiple @ExceptionHandler methods for different exception types.
Use @ControllerAdvice to handle exceptions globally across controllers.
Always return meaningful HTTP status codes to help clients understand the error.
@ExceptionHandler catches errors in controllers to avoid app crashes.
It lets you send friendly messages and proper HTTP status codes.
Use it to keep your controller code clean and user-friendly.
Practice
@ExceptionHandler in a Spring Boot controller?Solution
Step 1: Understand the role of @ExceptionHandler
@ExceptionHandler is used to catch exceptions that occur in controller methods to prevent the app from crashing.Step 2: Identify what @ExceptionHandler does in controllers
It allows sending user-friendly error messages and proper HTTP status codes when exceptions happen.Final Answer:
To catch and handle exceptions thrown in controller methods -> Option AQuick Check:
@ExceptionHandler catches exceptions [OK]
- Confusing @ExceptionHandler with URL mapping annotations
- Thinking it injects dependencies
- Assuming it configures database settings
Solution
Step 1: Identify the correct annotation for exception handling
@ExceptionHandler is the annotation used to mark methods that handle exceptions.Step 2: Check the method signature
The method should be annotated with @ExceptionHandler(Exception.class) and return a response, here a String view name.Final Answer:
@ExceptionHandler(Exception.class) public String handleError() { return "error"; } -> Option DQuick Check:
@ExceptionHandler syntax [OK]
- Using @RequestMapping or @GetMapping instead of @ExceptionHandler
- Misusing @Autowired annotation
- Missing the exception class in @ExceptionHandler
NullPointerException occurs?@RestController
public class MyController {
@GetMapping("/test")
public String test() {
throw new NullPointerException("Null error");
}
@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleNullPointer() {
return "Null pointer error handled";
}
}Solution
Step 1: Identify the exception and handler
The controller throws NullPointerException, which is caught by the method annotated with @ExceptionHandler(NullPointerException.class).Step 2: Check the response status annotation
The handler method has @ResponseStatus(HttpStatus.BAD_REQUEST), so it sets the HTTP status to 400.Final Answer:
400 Bad Request -> Option BQuick Check:
@ResponseStatus sets HTTP code = 400 [OK]
- Assuming default 500 error without @ResponseStatus
- Confusing exception type with HTTP status
- Ignoring the @ExceptionHandler method
@RestController
public class DemoController {
@GetMapping("/demo")
public String demo() {
throw new IllegalArgumentException("Invalid argument");
}
@ExceptionHandler(NullPointerException.class)
public String handleNull() {
return "Null error";
}
}What will happen when the
/demo endpoint is called?Solution
Step 1: Identify the thrown exception
The method throws IllegalArgumentException, but the handler only catches NullPointerException.Step 2: Check if exception is handled
Since no handler matches IllegalArgumentException, Spring Boot returns a default 500 Internal Server Error.Final Answer:
The exception will not be handled and a 500 error is returned -> Option CQuick Check:
Handler mismatch causes 500 error [OK]
- Assuming handler catches all exceptions
- Thinking handler method runs for different exception types
- Expecting 404 instead of 500 error
RuntimeException for all controllers and returns a JSON error message with HTTP status 500. Which approach correctly achieves this?Solution
Step 1: Understand global exception handling
@ControllerAdvice allows defining exception handlers that apply to all controllers globally.Step 2: Define handler method for RuntimeException
Use @ExceptionHandler(RuntimeException.class) with @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) to set status 500 and return JSON response.Final Answer:
Create a class annotated with @ControllerAdvice and define a method with @ExceptionHandler(RuntimeException.class) returning a JSON response and @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR). -> Option AQuick Check:
Global handler uses @ControllerAdvice + @ExceptionHandler [OK]
- Putting handlers only inside controllers for global effect
- Using application.properties for exception handling
- Not setting proper HTTP status in handler
Ready to prove it?
Pass the test and this pattern moves unknown
