Spring BootException Handlingintermediate
Updated:

Spring Boot Exception Handling Interview Questions and Answers

7 min read

Exception handling questions Spring interviewers ask — @RestControllerAdvice, @ExceptionHandler, @ResponseStatus, validation errors and ProblemDetail (RFC 7807).

TL;DR – Quick Answer

Spring Boot exception handling interviews test how you turn exceptions into clean HTTP responses: @RestControllerAdvice with @ExceptionHandler for centralized handling, @ResponseStatus for simple mappings, and ResponseEntityExceptionHandler for Spring MVC exceptions. Senior follow-ups cover handling @Valid failures via MethodArgumentNotValidException, returning RFC 7807 ProblemDetail (Spring 6, application/problem+json), most-specific-exception matching, and never leaking stack traces to clients.

On This Page

Exception handling is where a Spring Boot API stops being a demo and starts being production-grade. Interviewers ask about it because the way you turn an exception into an HTTP response — the status code, the body shape, what you hide — reveals whether you have shipped an API real clients depend on. This set covers the questions asked in intermediate rounds: centralized handling with @RestControllerAdvice, @ExceptionHandler and @ResponseStatus, validation errors, RFC 7807 ProblemDetail, exception matching, and not leaking internals — each with a spoken answer and the follow-up interviewers reach for.

Why interviewers ask about exception handling

An API is judged as much by its failures as its successes. Consistent status codes, structured error bodies, and no leaked stack traces are what make an API usable and safe for the callers on the other side. Exception handling questions test whether you centralize that concern properly or scatter try/catch through controllers and let raw exceptions escape. The mechanics are specific, so the answers are checkable.

Q1. How do you handle exceptions globally in Spring Boot?

With a class annotated @RestControllerAdvice containing @ExceptionHandler methods. The advice intercepts exceptions thrown from any controller and maps each exception type to a structured HTTP response in one place, so controllers stay focused on the happy path and error handling is centralized and consistent.

@RestControllerAdvice is @ControllerAdvice plus @ResponseBody, so whatever a handler returns is serialized as the JSON response body — exactly what an API needs. Each @ExceptionHandler declares which exception type it handles.

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(new ErrorResponse("NOT_FOUND", ex.getMessage()));
    }
}

Interview note: Follow-up: "difference between @ControllerAdvice and @RestControllerAdvice?" @RestControllerAdvice adds @ResponseBody, so handler return values become the response body. Plain @ControllerAdvice would try to resolve a view instead — wrong for a REST API.

Q2. @ExceptionHandler vs @ResponseStatus — when do you use each?

@ExceptionHandler is a method that catches a specific exception and builds the full response — status, body and headers under your control. @ResponseStatus is an annotation that maps an exception class (or handler) to a fixed HTTP status with no custom body. Use @ResponseStatus for trivial mappings and @ExceptionHandler when you need a structured error payload.

@ResponseStatus on a custom exception is the quickest way to get the right status code, but it produces the default error body. When clients need a machine-readable error with a code and details, you graduate to an @ExceptionHandler.

@ResponseStatus(HttpStatus.NOT_FOUND)          // simple: just the status
class ResourceNotFoundException extends RuntimeException {
    ResourceNotFoundException(String msg) { super(msg); }
}

Interview note: Trap: "if both @ResponseStatus on the exception and a matching @ExceptionHandler exist, which wins?" The @ExceptionHandler — an explicit handler takes over completely and decides the status and body itself.

Q3. How do you handle validation errors from @Valid?

When @Valid on a request body fails, Spring throws MethodArgumentNotValidException. You handle it in @RestControllerAdvice, extract the field errors from its BindingResult, and return a 400 response listing each invalid field and its message, so the client knows exactly what to correct.

The default validation error response is noisy and not tailored to your API; a dedicated handler turns it into a clean, predictable contract. This is one of the most common real-world handlers, so interviewers expect you to write it.

@ExceptionHandler(MethodArgumentNotValidException.class)
ResponseEntity<Map<String, String>> handleValidation(MethodArgumentNotValidException ex) {
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getFieldErrors()
      .forEach(fe -> errors.put(fe.getField(), fe.getDefaultMessage()));
    return ResponseEntity.badRequest().body(errors);
}

The @Valid trigger sits on the controller parameter:

@PostMapping("/users")
User create(@Valid @RequestBody CreateUserRequest request) { /* ... */ }

Interview note: Follow-up: "what exception comes from a failed @Valid on a @RequestBody versus a bad query parameter?" A request body gives MethodArgumentNotValidException; a constraint-violated @RequestParam/@PathVariable (with @Validated on the class) gives ConstraintViolationException. Handling both is the complete answer.

Q4. What is ProblemDetail and RFC 7807?

ProblemDetail is Spring 6's built-in implementation of RFC 7807, the standard for HTTP error responses. It returns an application/problem+json body with standard fields — type, title, status, detail, instance — plus custom properties, giving your API one consistent, machine-readable error shape instead of hand-rolled JSON.

Adopting ProblemDetail means every error across the API looks the same to clients, which is a real interoperability win. You can build it directly in a handler and add domain-specific properties.

@ExceptionHandler(ResourceNotFoundException.class)
ProblemDetail handleNotFound(ResourceNotFoundException ex) {
    ProblemDetail problem = ProblemDetail.forStatusAndDetail(
            HttpStatus.NOT_FOUND, ex.getMessage());
    problem.setTitle("Resource Not Found");
    problem.setProperty("resourceId", ex.getResourceId());
    return problem;   // serialized as application/problem+json
}

Interview note: Follow-up: "how do you turn on RFC 7807 for Spring's own MVC exceptions?" Set spring.mvc.problemdetails.enabled=true, and Spring returns ProblemDetail bodies for framework exceptions like 404 and 405 without you writing a handler for each.

Q5. What is ResponseEntityExceptionHandler and why extend it?

ResponseEntityExceptionHandler is a base class with @ExceptionHandler methods already written for Spring MVC's built-in exceptions — MethodArgumentNotValidException, HttpMessageNotReadableException, HttpRequestMethodNotSupportedException and more. You extend it in your @RestControllerAdvice and override just the methods you want to customize, so you handle framework exceptions consistently without reimplementing them.

It gives you a uniform error shape across both your custom exceptions and Spring's internal ones. In Spring 6 its methods already return ProblemDetail, so extending it aligns your API with RFC 7807 by default.

@RestControllerAdvice
class ApiExceptionHandler extends ResponseEntityExceptionHandler {
    // override handleMethodArgumentNotValid(...) to shape validation errors,
    // add your own @ExceptionHandler methods for domain exceptions
}

Interview note: Trap: "why might your custom validation handler never fire when extending ResponseEntityExceptionHandler?" The base class already handles MethodArgumentNotValidException, so you must override its method rather than add a competing @ExceptionHandler for the same type.

Q6. How does Spring match an exception to a handler?

Spring picks the handler for the most specific matching exception type. If you have handlers for both RuntimeException and a subclass like IllegalArgumentException, a thrown IllegalArgumentException goes to the subclass handler. A handler for a supertype catches all its subtypes unless a more specific handler exists.

This lets you write a broad catch-all for Exception as a safety net returning 500, plus narrow handlers for the exceptions you care about — and trust that the narrow ones win. Controller-local @ExceptionHandler methods take precedence over global @RestControllerAdvice for the same exception.

@ExceptionHandler(Exception.class)              // catch-all safety net → 500
ProblemDetail handleUnexpected(Exception ex) {
    return ProblemDetail.forStatusAndDetail(
            HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
}

Interview note: Follow-up: "global advice and a controller-local handler both match — which runs?" The controller-local @ExceptionHandler wins; global advice is the fallback for exceptions the controller does not handle itself.

Q7. How do you avoid leaking stack traces and internal details?

Never put exception internals or stack traces in the response body. Return a controlled message and status from your handlers, log the full exception server-side with a correlation id, and let the catch-all handler return a generic 500 for anything unexpected. Clients get a safe, useful error; operators get the detail in the logs.

Leaking a stack trace exposes class names, framework versions and sometimes SQL — a security and professionalism failure. The pattern is: specific handlers return specific safe messages; the Exception catch-all returns a generic message while logging everything.

@ExceptionHandler(Exception.class)
ProblemDetail handleUnexpected(Exception ex) {
    log.error("Unhandled exception", ex);       // full detail in logs only
    return ProblemDetail.forStatusAndDetail(
            HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong");  // safe for client
}

Interview note: Trap: "should you set server.error.include-stacktrace=always in production?" No — keep it never (or on-param) in production so stack traces never reach clients. always is a debugging-only convenience.

Q8. What is the whitelabel error page and how do you customize the default error path?

The whitelabel error page is Spring Boot's default fallback error response when no other handler applies. For APIs you replace it with @RestControllerAdvice; you tune the default via server.error.* properties (for example server.error.include-message), or take full control by implementing the ErrorController interface to define the /error endpoint's behaviour.

Most APIs never want the whitelabel page — a browser-oriented HTML error — so exhaustive @RestControllerAdvice plus a catch-all is the usual answer. ErrorController is for when you need to own the framework's default error dispatch entirely.

Interview note: Follow-up: "your custom handlers cover known exceptions but an unmapped error still shows the whitelabel page — how do you fix it?" Add an @ExceptionHandler(Exception.class) catch-all in your advice so nothing falls through to the default error path.

How to prepare

Write one @RestControllerAdvice end to end: a MethodArgumentNotValidException handler that returns field errors, a domain-exception handler returning a ProblemDetail, and an Exception catch-all that logs and returns a safe 500. Then hit the endpoints with bad input and watch the shapes come back — doing it once turns the validation and RFC 7807 answers into something you have built rather than recited, and those two are the most common deep follow-ups.

Ground the web-layer concepts on the Spring Boot learning path, and read this alongside Spring MVC and Spring Data JPA, since request handling and persistence are where most of the exceptions you will map actually originate. A focused mock interview on API error handling is the fastest way to find whether your handler-and-precedence story survives the "and what about this exception?" follow-ups.

Frequently Asked Questions

What is @ControllerAdvice used for?
@ControllerAdvice defines cross-cutting concerns — mainly global exception handling with @ExceptionHandler methods — that apply across all controllers. @RestControllerAdvice is the same thing plus @ResponseBody, so its handler return values are serialized as the response body, which is what you want for REST APIs.
What is the difference between @ExceptionHandler and @ResponseStatus?
@ExceptionHandler is a method that catches a given exception and builds the response, giving you full control over status, body and headers. @ResponseStatus is a simpler annotation on an exception class or handler that maps it to a fixed HTTP status with no custom body. Use @ResponseStatus for trivial mappings and @ExceptionHandler when you need a structured error response.
How do you handle validation errors from @Valid?
When @Valid fails on a request body, Spring throws MethodArgumentNotValidException. Handle it in @RestControllerAdvice, read the BindingResult for field errors, and return a structured 400 response listing each invalid field and message, so the client learns exactly what to fix.
What is ProblemDetail in Spring Boot?
ProblemDetail is Spring 6's built-in implementation of RFC 7807, the standard format for HTTP error responses. It produces an application/problem+json body with fields like type, title, status, detail and instance, giving APIs a consistent, machine-readable error shape instead of ad-hoc JSON.
What is the whitelabel error page?
The whitelabel error page is Spring Boot's default fallback error response, served by its built-in error handling when no other handler applies. You replace it with @RestControllerAdvice for APIs, tune it through the server.error.* properties, or implement ErrorController for full control over the default error path.

Want to Build Your Career in Java Full Stack with AI?

Join CodeBegun and train with working industry engineers — Explore the Java Full Stack program

Apply for Demo Class →
Siva Prasad Galaba
Founder, CodeBegun · Staff Engineer

Founder of CodeBegun. 15+ years building Java systems at companies like Crunchyroll. Teaches Java, Spring Boot and system design the way the industry actually works, and mentors students through projects, mock interviews and placement preparation.

Technically reviewed by CodeBegun Technical TeamLast reviewed 16 July 2026 LinkedIn
Chat with us