Bird
0
0

Which of the following is the correct way to declare a global exception handler method inside a @ControllerAdvice class?

easy📝 Syntax Q12 of 15
Spring Boot - Exception Handling
Which of the following is the correct way to declare a global exception handler method inside a @ControllerAdvice class?
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"; }
Step-by-Step Solution
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]
Quick Trick: 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes