Bird
Raised Fist0
Spring Bootframework~20 mins

@ControllerAdvice for global handling in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
ControllerAdvice Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an exception is thrown in a controller with @ControllerAdvice?
Consider a Spring Boot application with a @ControllerAdvice class that handles NullPointerException globally. What will happen if a controller method throws a NullPointerException?
Spring Boot
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<String> handleNullPointer(Exception ex) {
        return ResponseEntity.status(400).body("Null pointer error caught globally");
    }
}

// In some controller:
// public String someMethod() {
//     throw new NullPointerException();
// }
AThe global handler method handleNullPointer will catch the exception and return a 400 response with the message.
BThe exception will propagate and cause a server error 500 without using the global handler.
CThe application will crash because @ControllerAdvice cannot handle NullPointerException.
DThe exception will be ignored and the controller will return a successful empty response.
Attempts:
2 left
💡 Hint
Think about how @ControllerAdvice works for exceptions thrown in controllers.
📝 Syntax
intermediate
1:30remaining
Which @ExceptionHandler method signature is correct inside @ControllerAdvice?
You want to handle IllegalArgumentException globally. Which method signature is valid inside a @ControllerAdvice class?
Apublic ResponseEntity<String> handleIllegalArg(IllegalArgumentException ex)
Bpublic void handleIllegalArg() throws IllegalArgumentException
Cpublic String handleIllegalArg(Exception ex, HttpServletRequest req)
Dpublic int handleIllegalArg(IllegalArgumentException ex)
Attempts:
2 left
💡 Hint
The method should accept the exception type and return a response type.
🔧 Debug
advanced
2:00remaining
Why is the global exception handler not catching exceptions?
Given this @ControllerAdvice class, exceptions thrown in controllers are not caught. What is the likely cause? @ControllerAdvice public class GlobalHandler { @ExceptionHandler(RuntimeException.class) public String handleRuntime(RuntimeException ex) { return "Error caught"; } } Controllers throw IllegalArgumentException which extends RuntimeException.
AThe @ExceptionHandler method must handle IllegalArgumentException explicitly, not RuntimeException.
BThe exception is not caught because IllegalArgumentException is not a RuntimeException.
CThe @ControllerAdvice class must be annotated with @Component to be detected.
DThe @ControllerAdvice class is missing @RestControllerAdvice annotation to handle REST responses.
Attempts:
2 left
💡 Hint
Consider the difference between @ControllerAdvice and @RestControllerAdvice for response bodies.
🧠 Conceptual
advanced
1:30remaining
What is the scope of @ControllerAdvice in a Spring Boot app?
Which statement best describes the scope of a class annotated with @ControllerAdvice?
A@ControllerAdvice applies only to controllers in the same package as the advice class.
B@ControllerAdvice applies globally to all controllers in the application by default.
C@ControllerAdvice applies only to controllers explicitly listed in its annotations.
D@ControllerAdvice applies only to controllers annotated with @RestController.
Attempts:
2 left
💡 Hint
Think about the default behavior of @ControllerAdvice without filters.
❓ state_output
expert
1:00remaining
What is the HTTP status code returned by this global handler?
Given this @ControllerAdvice handler: @ControllerAdvice public class GlobalErrorHandler { @ExceptionHandler(IllegalStateException.class) public ResponseEntity handleIllegalState(IllegalStateException ex) { return ResponseEntity.status(409).body("Conflict error"); } } If a controller throws IllegalStateException, what HTTP status code will the client receive?
A400
B500
C409
D200
Attempts:
2 left
💡 Hint
Look at the ResponseEntity.status() call in the handler.

Practice

(1/5)
1. What is the main purpose of using @ControllerAdvice in a Spring Boot application?
easy
A. To handle exceptions globally for all controllers in one place
B. To define REST endpoints for the application
C. To configure database connections
D. To create scheduled tasks

Solution

  1. Step 1: Understand the role of @ControllerAdvice

    @ControllerAdvice is a special annotation in Spring Boot that allows you to write code to handle exceptions or apply logic across all controllers globally.
  2. Step 2: Identify its main use

    Its main use is to centralize exception handling so you don't have to repeat error handling code in every controller.
  3. Final Answer:

    To handle exceptions globally for all controllers in one place -> Option A
  4. Quick Check:

    @ControllerAdvice = global exception handling [OK]
Hint: Think global error handling for all controllers [OK]
Common Mistakes:
  • Confusing @ControllerAdvice with @RestController
  • Thinking it configures database or tasks
  • Assuming it defines endpoints
2. Which of the following is the correct way to declare a global exception handler method inside a @ControllerAdvice class?
easy
A. @Service public String handleError() { return "error"; }
B. @ExceptionHandler(Exception.class) public String handleError() { return "error"; }
C. @GetMapping public String handleError() { return "error"; }
D. @RequestMapping("/error") public String handleError() { return "error"; }

Solution

  1. Step 1: Identify the annotation for exception handling

    The correct annotation to handle exceptions globally is @ExceptionHandler with the exception class specified.
  2. Step 2: Check method signature and annotation usage

    @ExceptionHandler(Exception.class) public String handleError() { return "error"; } uses @ExceptionHandler(Exception.class) which is correct inside a @ControllerAdvice class to catch all exceptions.
  3. Final Answer:

    @ExceptionHandler(Exception.class) public String handleError() { return "error"; } -> Option B
  4. Quick Check:

    @ExceptionHandler = global exception method [OK]
Hint: Use @ExceptionHandler with exception class inside @ControllerAdvice [OK]
Common Mistakes:
  • Using @RequestMapping or @GetMapping instead of @ExceptionHandler
  • Missing exception class in @ExceptionHandler
  • Using @Service annotation incorrectly
3. Given the following code snippet, what will be the HTTP response status when a NullPointerException is thrown in any controller?
@ControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(NullPointerException.class)
  public ResponseEntity<String> handleNullPointer() {
    return new ResponseEntity<>("Null pointer error", HttpStatus.BAD_REQUEST);
  }
}
medium
A. 400 Bad Request with message "Null pointer error"
B. 500 Internal Server Error with default message
C. 200 OK with message "Null pointer error"
D. 404 Not Found with message "Null pointer error"

Solution

  1. Step 1: Analyze the @ExceptionHandler method

    The method handles NullPointerException and returns a ResponseEntity with message "Null pointer error" and status BAD_REQUEST.
  2. Step 2: Understand HTTP status returned

    HttpStatus.BAD_REQUEST corresponds to 400 status code, so the response will have status 400 with the given message.
  3. Final Answer:

    400 Bad Request with message "Null pointer error" -> Option A
  4. Quick Check:

    @ExceptionHandler returns 400 status [OK]
Hint: Check ResponseEntity status in @ExceptionHandler method [OK]
Common Mistakes:
  • Assuming default 500 error instead of specified status
  • Confusing 400 with 200 OK
  • Ignoring the returned ResponseEntity status
4. Consider this @ControllerAdvice class:
@ControllerAdvice
public class GlobalHandler {
  @ExceptionHandler(IllegalArgumentException.class)
  public String handleIllegalArgument() {
    return "illegal";
  }

  @ExceptionHandler(Exception.class)
  public String handleAll() {
    return "error";
  }
}

What is the problem if a NullPointerException occurs in a controller?
medium
A. NullPointerException is not handled and causes server error
B. handleIllegalArgument() method will handle NullPointerException incorrectly
C. handleAll() method will handle NullPointerException correctly
D. Compilation error due to multiple @ExceptionHandler methods

Solution

  1. Step 1: Identify exception handlers and their scopes

    handleIllegalArgument() handles IllegalArgumentException only; handleAll() handles all Exceptions as a fallback.
  2. Step 2: Determine which method handles NullPointerException

    Since NullPointerException is not IllegalArgumentException, handleAll() will catch it as it handles Exception class.
  3. Final Answer:

    handleAll() method will handle NullPointerException correctly -> Option C
  4. Quick Check:

    More specific handlers first, then general Exception handler [OK]
Hint: General @ExceptionHandler(Exception.class) catches all others [OK]
Common Mistakes:
  • Thinking NullPointerException is unhandled
  • Assuming multiple handlers cause compile error
  • Confusing which handler matches which exception
5. You want to create a global error handler that returns JSON with error details for all exceptions except ResourceNotFoundException, which should return 404 status with a custom message. How should you implement this using @ControllerAdvice?
hard
A. Use a single @ExceptionHandler(Exception.class) method and check exception type inside to return different responses
B. Use @ControllerAdvice only for ResourceNotFoundException and ignore other exceptions
C. Handle ResourceNotFoundException in each controller separately, and use @ControllerAdvice only for other exceptions
D. Create two @ExceptionHandler methods: one for ResourceNotFoundException returning 404 JSON, another for Exception returning generic JSON with 500 status

Solution

  1. Step 1: Understand requirement for specific and general handling

    You need one handler for ResourceNotFoundException with 404 and custom JSON, and another for all other exceptions with generic 500 JSON.
  2. Step 2: Implement two separate @ExceptionHandler methods in @ControllerAdvice

    One method annotated with @ExceptionHandler(ResourceNotFoundException.class) returns 404 JSON; another with @ExceptionHandler(Exception.class) returns 500 JSON.
  3. Final Answer:

    Create two @ExceptionHandler methods: one for ResourceNotFoundException returning 404 JSON, another for Exception returning generic JSON with 500 status -> Option D
  4. Quick Check:

    Separate handlers for specific and general exceptions [OK]
Hint: Use multiple @ExceptionHandler methods for different exceptions [OK]
Common Mistakes:
  • Using one method with manual type checks inside
  • Handling specific exceptions in controllers, not globally
  • Ignoring general exceptions in @ControllerAdvice
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard