Java Tutorial 0/145 lessons ~6 min read Lesson 65

    Global Exception Handling

    global exception handling a @controlleradvice class centralises exception-to-http-response mapping across all controllers. no more try/catch in every endpoint — one place handles

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    A @ControllerAdvice class centralises exception-to-HTTP-response mapping across all controllers. No more try/catch in every endpoint — one place handles validation errors, not-found, auth failures and unexpected exceptions.

    Informative example

    Centralised error responses:

    ts
    @RestControllerAdvice
    public class GlobalExceptionHandler {
    @ExceptionHandler(ResourceNotFoundException.class)
    ResponseEntity<ErrorResponse> notFound(ResourceNotFoundException ex) {
    return ResponseEntity.status(404)
    .body(new ErrorResponse("NOT_FOUND", ex.getMessage()));
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ResponseEntity<ErrorResponse> validation(MethodArgumentNotValidException ex) {
    var errors = ex.getBindingResult().getFieldErrors().stream()
    .collect(toMap(FieldError::getField, FieldError::getDefaultMessage));
    return ResponseEntity.badRequest()
    .body(new ErrorResponse("VALIDATION_FAILED", errors));
    }
    @ExceptionHandler(Exception.class)
    ResponseEntity<ErrorResponse> fallback(Exception ex) {
    log.error("Unhandled", ex);
    return ResponseEntity.status(500)
    .body(new ErrorResponse("INTERNAL_ERROR", "Something went wrong"));
    }
    }

    Best practices

    • Never expose stack traces to clients in production.
    • Use consistent error response shape: code, message, details, timestamp.
    • Log the full exception server-side; return safe message client-side.

    Purpose of this lesson

    Master Global Exception Handling so you can apply it confidently in production Java code, technical interviews, and code reviews.

    Step-by-step explanation

    1. Understand the core idea behind Global Exception Handling.
    2. Walk through the runnable example and tweak it in the playground.
    3. Apply the pattern in a small Spring Boot or CLI exercise of your own.
    4. Re-read the common mistakes and interview Q&A to lock the concept in.

    Interactive workflow diagram

    1Global Exception Handling — typical flow
    1 / 4

    Identify use case

    Recognize when global exception handling is the right tool for the problem.

    Useful template

    RFC 7807 ProblemDetail

    java
    @ExceptionHandler(ResourceNotFoundException.class)
    ProblemDetail notFound(ResourceNotFoundException ex) {
    return ProblemDetail.forStatusAndDetail(NOT_FOUND, ex.getMessage());
    }

    Debugging tips

    • Read the full stack trace — Java's exception messages name the offending class and line.
    • Reproduce in the smallest possible main() method before fixing in the real app.
    • Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering System.out.

    Optimization strategies

    • Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
    • Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
    • Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.

    Enterprise example

    Teams at Netflix, Uber and Goldman Sachs apply Global Exception Handling daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).

    Interview questions & answers

    Q1Explain Global Exception Handling in one minute.
    Describe what problem it solves, the JDK APIs involved, and one production trade-off.
    Q2When would you avoid Global Exception Handling?
    Mention performance, complexity, or readability cases where a simpler approach wins.

    Summary

    In this lesson you learned Global Exception Handling — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.

    Ready to mark this lesson complete?Track your journey across the entire course.