Close
« Tutorial

Spring MVC - @ExceptionHandler MCQ

0/13
0 ✓
0 ✗

1. What is @ExceptionHandler mainly used for?

2. Where do we normally put @ExceptionHandler inside a controller?

3. A controller has only one exception handler, declared for Exception. A request method in the same controller throws a RuntimeException. What happens?

4. Which two attribute names of @ExceptionHandler can be used to give the handled exception types? They are interchangeable.

5. What does the produces attribute of @ExceptionHandler do?

6. The annotation below has no exception type. Which exception does this method handle?

@ExceptionHandler
@ResponseBody
public String handle(IOException e) {
    return "IO problem";
}

7. Since Spring 6, which return type can an exception handler method use to produce a standard RFC 9457 problem details response?

8. An @ExceptionHandler method is defined directly inside a controller class. Which exceptions does it handle?

9. We want these exception handler methods to apply to all controllers. Which annotation should we put on the class?

public class GlobalErrors {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handle(Exception e) {
        return "Error";
    }
}

10. Both methods below are in the same controller. What problem does this cause?

@ExceptionHandler(IllegalStateException.class)
@ResponseBody
public String first(IllegalStateException e) {
    return "first";
}

@ExceptionHandler(IllegalStateException.class)
@ResponseBody
public String second(IllegalStateException e) {
    return "second";
}

11. Which class resolves exceptions and invokes @ExceptionHandler methods by default?

12. Which exceptions can the exception parameter of an @ExceptionHandler method match?

13. What does a Model parameter contain when it is used in an @ExceptionHandler method?

14. A client sends a request to /test/abc. What is the response body?

@GetMapping("/test/{id}")
@ResponseBody
public String test(@PathVariable String id) {
    return "id " + Integer.parseInt(id);
}

@ExceptionHandler(NumberFormatException.class)
@ResponseBody
public String onNumber(NumberFormatException e) {
    return "Bad number";
}

@ExceptionHandler(Exception.class)
@ResponseBody
public String onAny(Exception e) {
    return "Failed";
}

15. A client sends a request to /data/1985. What is the response?

@GetMapping("/data/{year}")
@ResponseBody
public String data(@PathVariable int year) throws Exception {
    if (year < 1990) {
        throw new Exception("Too old: " + year);
    }
    return "data " + year;
}

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
@ResponseBody
public String onError(Exception e) {
    return "Error: " + e.getMessage();
}
Join