0
0
Spring Bootframework~5 mins

@ExceptionHandler in controllers in Spring Boot

Choose your learning style9 modes available
Introduction

@ExceptionHandler helps you catch and handle errors in your web app controllers so users see friendly messages instead of crashes.

When you want to show a custom error message if a user requests a missing page.
When you want to handle invalid input errors gracefully in your API.
When you want to log errors and return a specific HTTP status code.
When you want to keep your controller methods clean by separating error handling.
When you want to return different responses for different types of exceptions.
Syntax
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.

Examples
This handles NullPointerException and returns a 400 Bad Request with a message.
Spring Boot
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<String> handleNullPointer(NullPointerException ex) {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Null value found!");
}
This catches all exceptions not handled elsewhere and returns a 500 error.
Spring Boot
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Something went wrong.");
}
Sample Program

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.

Spring Boot
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.");
    }
}
OutputSuccess
Important Notes

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.

Summary

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