Bird
Raised Fist0
Spring Bootframework~10 mins

@ExceptionHandler in controllers in Spring Boot - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to handle exceptions in a Spring Boot controller method.

Spring Boot
public class MyController {
    @[1]
    public ResponseEntity<String> handleException(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error occurred");
    }
}
Drag options to blanks, or click blank then click option'
ARequestMapping
BPostMapping
CGetMapping
DExceptionHandler
Attempts:
3 left
💡 Hint
Common Mistakes
Using @GetMapping or @PostMapping instead of @ExceptionHandler
Forgetting to annotate the method
2fill in blank
medium

Complete the code to specify which exception type the handler method should catch.

Spring Boot
@ExceptionHandler([1].class)
public ResponseEntity<String> handleNotFound(Exception ex) {
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Resource not found");
}
Drag options to blanks, or click blank then click option'
AResourceNotFoundException
BRuntimeException
CNullPointerException
DIOException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a general exception like RuntimeException instead of a specific one
Not specifying the exception class
3fill in blank
hard

Fix the error in the exception handler method signature to correctly handle exceptions.

Spring Boot
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleException([1] ex) {
    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
Drag options to blanks, or click blank then click option'
AString
BException
CResourceNotFoundException
DHttpServletRequest
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic Exception type when a specific exception is declared
Using unrelated types like String or HttpServletRequest
4fill in blank
hard

Fill both blanks to create a global exception handler class with proper annotations.

Spring Boot
@[1]
public class GlobalExceptionHandler {
    @[2]
    public ResponseEntity<String> handleAllExceptions(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Server error");
    }
}
Drag options to blanks, or click blank then click option'
AControllerAdvice
BRestController
CExceptionHandler
DService
Attempts:
3 left
💡 Hint
Common Mistakes
Using @RestController instead of @ControllerAdvice for global handling
Missing @ExceptionHandler on the method
5fill in blank
hard

Fill all three blanks to handle a specific exception and return a custom message with status.

Spring Boot
@ExceptionHandler([1].class)
public ResponseEntity<String> handleCustomException([2] ex) {
    return ResponseEntity.status([3]).body("Custom error: " + ex.getMessage());
}
Drag options to blanks, or click blank then click option'
ACustomException
CHttpStatus.BAD_REQUEST
DHttpStatus.NOT_FOUND
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatching exception class and parameter type
Using wrong HTTP status codes

Practice

(1/5)
1. What is the main purpose of using @ExceptionHandler in a Spring Boot controller?
easy
A. To catch and handle exceptions thrown in controller methods
B. To define the URL path for a controller method
C. To inject dependencies into the controller
D. To configure database connections

Solution

  1. Step 1: Understand the role of @ExceptionHandler

    @ExceptionHandler is used to catch exceptions that occur in controller methods to prevent the app from crashing.
  2. Step 2: Identify what @ExceptionHandler does in controllers

    It allows sending user-friendly error messages and proper HTTP status codes when exceptions happen.
  3. Final Answer:

    To catch and handle exceptions thrown in controller methods -> Option A
  4. Quick Check:

    @ExceptionHandler catches exceptions [OK]
Hint: Remember: @ExceptionHandler handles errors in controllers [OK]
Common Mistakes:
  • Confusing @ExceptionHandler with URL mapping annotations
  • Thinking it injects dependencies
  • Assuming it configures database settings
2. Which of the following is the correct way to declare an exception handler method in a Spring Boot controller?
easy
A. @RequestMapping(Exception.class) public String handleError() { return "error"; }
B. @GetMapping(Exception.class) public String handleError() { return "error"; }
C. @Autowired(Exception.class) public String handleError() { return "error"; }
D. @ExceptionHandler(Exception.class) public String handleError() { return "error"; }

Solution

  1. Step 1: Identify the correct annotation for exception handling

    @ExceptionHandler is the annotation used to mark methods that handle exceptions.
  2. Step 2: Check the method signature

    The method should be annotated with @ExceptionHandler(Exception.class) and return a response, here a String view name.
  3. Final Answer:

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

    @ExceptionHandler syntax [OK]
Hint: Use @ExceptionHandler with exception class to handle errors [OK]
Common Mistakes:
  • Using @RequestMapping or @GetMapping instead of @ExceptionHandler
  • Misusing @Autowired annotation
  • Missing the exception class in @ExceptionHandler
3. Given the following controller code snippet, what will be the HTTP status code returned when a NullPointerException occurs?
@RestController
public class MyController {
  @GetMapping("/test")
  public String test() {
    throw new NullPointerException("Null error");
  }

  @ExceptionHandler(NullPointerException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public String handleNullPointer() {
    return "Null pointer error handled";
  }
}
medium
A. 200 OK
B. 400 Bad Request
C. 500 Internal Server Error
D. 404 Not Found

Solution

  1. Step 1: Identify the exception and handler

    The controller throws NullPointerException, which is caught by the method annotated with @ExceptionHandler(NullPointerException.class).
  2. Step 2: Check the response status annotation

    The handler method has @ResponseStatus(HttpStatus.BAD_REQUEST), so it sets the HTTP status to 400.
  3. Final Answer:

    400 Bad Request -> Option B
  4. Quick Check:

    @ResponseStatus sets HTTP code = 400 [OK]
Hint: Look for @ResponseStatus on @ExceptionHandler method [OK]
Common Mistakes:
  • Assuming default 500 error without @ResponseStatus
  • Confusing exception type with HTTP status
  • Ignoring the @ExceptionHandler method
4. Consider this controller code snippet:
@RestController
public class DemoController {
  @GetMapping("/demo")
  public String demo() {
    throw new IllegalArgumentException("Invalid argument");
  }

  @ExceptionHandler(NullPointerException.class)
  public String handleNull() {
    return "Null error";
  }
}

What will happen when the /demo endpoint is called?
medium
A. The exception will be handled by handleNull method
B. The response will be "Null error" with HTTP 200
C. The exception will not be handled and a 500 error is returned
D. The server will return HTTP 404 Not Found

Solution

  1. Step 1: Identify the thrown exception

    The method throws IllegalArgumentException, but the handler only catches NullPointerException.
  2. Step 2: Check if exception is handled

    Since no handler matches IllegalArgumentException, Spring Boot returns a default 500 Internal Server Error.
  3. Final Answer:

    The exception will not be handled and a 500 error is returned -> Option C
  4. Quick Check:

    Handler mismatch causes 500 error [OK]
Hint: Handler must match exception type exactly [OK]
Common Mistakes:
  • Assuming handler catches all exceptions
  • Thinking handler method runs for different exception types
  • Expecting 404 instead of 500 error
5. You want to create a global exception handler in Spring Boot that catches RuntimeException for all controllers and returns a JSON error message with HTTP status 500. Which approach correctly achieves this?
hard
A. Create a class annotated with @ControllerAdvice and define a method with @ExceptionHandler(RuntimeException.class) returning a JSON response and @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR).
B. Add @ExceptionHandler(RuntimeException.class) method inside each controller class returning a view name.
C. Use @RestController on a class with @ExceptionHandler(Exception.class) returning a String message.
D. Configure exception handling in application.properties file.

Solution

  1. Step 1: Understand global exception handling

    @ControllerAdvice allows defining exception handlers that apply to all controllers globally.
  2. Step 2: Define handler method for RuntimeException

    Use @ExceptionHandler(RuntimeException.class) with @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) to set status 500 and return JSON response.
  3. Final Answer:

    Create a class annotated with @ControllerAdvice and define a method with @ExceptionHandler(RuntimeException.class) returning a JSON response and @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR). -> Option A
  4. Quick Check:

    Global handler uses @ControllerAdvice + @ExceptionHandler [OK]
Hint: Use @ControllerAdvice for global exception handling [OK]
Common Mistakes:
  • Putting handlers only inside controllers for global effect
  • Using application.properties for exception handling
  • Not setting proper HTTP status in handler
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