How do you handle exceptions in Spring Boot applications?

Exception handling in Spring Boot is used to manage application errors in a centralized and consistent manner. Instead of handling exceptions in every controller method, Spring Boot provides mechanisms such as @ExceptionHandler, @ControllerAdvice, and @RestControllerAdvice to catch exceptions globally and return meaningful error responses to clients.

Key Points: • Centralized exception handling improves code maintainability. • @ExceptionHandler is used to handle specific exceptions. • @ControllerAdvice and @RestControllerAdvice provide global exception handling. • Custom error responses improve API usability and debugging. • Proper exception handling prevents exposing internal application details.

Why Do We Need Exception Handling?

Without proper exception handling:

• Applications may return confusing error messages. • Clients receive inconsistent responses. • Sensitive implementation details may be exposed. • Debugging becomes difficult.

Good exception handling ensures predictable and user-friendly error responses.

Common Exception Handling Approaches

1. Using @ExceptionHandler

This annotation handles specific exceptions within a controller.

Code Example:

@RestController
public class EmployeeController {

    @ExceptionHandler(

EmployeeNotFoundException.class)

    public String handleException(
            EmployeeNotFoundException ex) {

        return ex.getMessage();
    }
}

Whenever EmployeeNotFoundException occurs, this method is executed.

2. Using Global Exception Handling

For enterprise applications, global exception handling is preferred.

Code Example:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(

EmployeeNotFoundException.class)

    public ResponseEntity<String>
            handleEmployeeException(
                    EmployeeNotFoundException ex) {

return ResponseEntity .status(HttpStatus.NOT_FOUND)

                .body(ex.getMessage());
    }
}

This handles exceptions across all controllers.

Why Use @RestControllerAdvice?

Benefits:

• Centralized error handling • Reduced code duplication • Consistent API responses • Easier maintenance

Instead of writing exception handlers in every controller, all exception logic is placed in one class.

Handling Multiple Exceptions

Code Example:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(

NullPointerException.class)

    public ResponseEntity<String>
            handleNullPointerException(
                    NullPointerException ex) {

return ResponseEntity .badRequest()

                .body("Null value encountered");
    }

    @ExceptionHandler(

Exception.class)

    public ResponseEntity<String>
            handleGenericException(
                    Exception ex) {

return ResponseEntity .status( HttpStatus.INTERNAL_SERVER_ERROR)

                .body("Something went wrong");
    }
}

Different exceptions can return different responses.

Custom Error Response

Instead of returning plain text, APIs usually return structured JSON.

Code Example:

public class ErrorResponse {

    private String message;
    private int status;

    public ErrorResponse(

String message,

            int status) {

        this.message = message;
        this.status = status;
    }
}

Exception Handler:

@ExceptionHandler( EmployeeNotFoundException.class)

public ResponseEntity<ErrorResponse>
        handleException(
                EmployeeNotFoundException ex) {

    ErrorResponse response =
            new ErrorResponse(
                    ex.getMessage(),
                    404);

return ResponseEntity .status(HttpStatus.NOT_FOUND)

            .body(response);
}

Response:

{ "message": "Employee not found", "status": 404 }

Handling Validation Errors

Spring Boot commonly uses:

@Valid

for request validation.

Example:

@PostMapping
public Employee createEmployee(
        @Valid
        @RequestBody Employee employee) {

    return employee;
}

Validation failures can also be handled globally using @ExceptionHandler.

How Exception Handling Works

Client Request | Controller | Exception Occurs | Exception Handler | Error Response Generated | Client Receives Response

This keeps the application stable and prevents unexpected crashes.

Example: Suppose a client requests:

GET /employees/101

If employee 101 does not exist:

EmployeeNotFoundException

is thrown.

Global Exception Handler catches it and returns:

{ "message": "Employee not found", "status": 404 }

Instead of an internal server error.

Benefits

• Cleaner controller code • Centralized error management • Consistent API responses • Better client experience • Easier debugging and maintenance

Real-World Example

In an e-commerce application:

Possible exceptions:

• ProductNotFoundException • OrderNotFoundException • PaymentFailedException

A global exception handler can catch all these exceptions and return standardized JSON responses, making the API easier for frontend and mobile applications to consume.

Interview Tip: A concise interview answer is:

"In Spring Boot, exceptions are commonly handled using @ExceptionHandler along with @ControllerAdvice or @RestControllerAdvice. This allows centralized exception handling across the application and helps return consistent, meaningful error responses with appropriate HTTP status codes."