Bird
Raised Fist0
Spring Bootframework~20 mins

Handling not found exceptions in Spring Boot - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Exception Mastery in Spring Boot
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a resource is not found in this Spring Boot controller?
Consider this Spring Boot REST controller method that fetches a user by ID. What will be the HTTP response status if the user is not found?
Spring Boot
@GetMapping("/users/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
    Optional<User> user = userService.findById(id);
    if (user.isPresent()) {
        return ResponseEntity.ok(user.get());
    } else {
        throw new UserNotFoundException("User not found");
    }
}
AHTTP 404 Not Found with a custom error message
BHTTP 500 Internal Server Error
CHTTP 200 OK with an empty body
DHTTP 400 Bad Request
Attempts:
2 left
💡 Hint
Think about what happens when an exception is thrown and how Spring Boot handles it by default or with custom handlers.
📝 Syntax
intermediate
2:00remaining
Which code snippet correctly defines a custom exception handler for not found exceptions in Spring Boot?
You want to return HTTP 404 when a UserNotFoundException is thrown. Which of these @ExceptionHandler methods is correct?
A
@ExceptionHandler(UserNotFoundException.class)
@ResponseBody
public ResponseEntity&lt;String&gt; handleUserNotFound() {
    return new ResponseEntity&lt;&gt;("User not found", HttpStatus.NOT_FOUND);
}
B
@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public void handleUserNotFound(UserNotFoundException ex) {
    return "User not found";
}
C
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleUserNotFound() {
    return "User not found";
}
D
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity&lt;String&gt; handleUserNotFound() {
    return new ResponseEntity&lt;&gt;("User not found", HttpStatus.NOT_FOUND);
}
Attempts:
2 left
💡 Hint
Remember that the method signature and return type must match the expected response type.
🔧 Debug
advanced
2:00remaining
Why does this global exception handler not return 404 for UserNotFoundException?
Given this global exception handler, why does the client receive HTTP 500 instead of 404 when UserNotFoundException is thrown?
Spring Boot
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleAllExceptions(Exception ex) {
        return "Error occurred";
    }
}
ABecause the handler catches all exceptions as 500, it overrides specific handlers and does not map UserNotFoundException to 404
BBecause UserNotFoundException is not a subclass of Exception, so it is not caught
CBecause @ResponseStatus is ignored in @ControllerAdvice classes
DBecause the method returns a String instead of ResponseEntity
Attempts:
2 left
💡 Hint
Think about exception handler specificity and how Spring chooses which handler to use.
❓ state_output
advanced
2:00remaining
What is the HTTP response body when this exception handler is triggered?
Given this exception handler, what will the client receive in the response body when UserNotFoundException is thrown?
Spring Boot
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public Map<String, String> handleUserNotFound(UserNotFoundException ex) {
    Map<String, String> error = new HashMap<>();
    error.put("error", ex.getMessage());
    return error;
}
A"User not found"
B{"error":"User not found"}
C{}
D<error>User not found</error>
Attempts:
2 left
💡 Hint
Consider the return type and how Spring converts it to JSON.
🧠 Conceptual
expert
3:00remaining
Why use @ResponseStatus on a custom exception class instead of handling it in a controller advice?
What is the main advantage of annotating a custom exception class with @ResponseStatus(HttpStatus.NOT_FOUND) compared to handling the exception in a @ControllerAdvice class?
AIt forces Spring Boot to log the exception stack trace every time it occurs
BIt disables the default error page and returns a blank response instead
CIt allows the exception to automatically trigger the specified HTTP status without extra handler code, simplifying controller logic
DIt makes the exception checked, so it must be declared or caught
Attempts:
2 left
💡 Hint
Think about how Spring Boot uses @ResponseStatus on exceptions during response generation.

Practice

(1/5)
1. What is the main purpose of handling not found exceptions in a Spring Boot application?
easy
A. To improve database performance
B. To log all user activities
C. To automatically retry failed requests
D. To return a clear 404 status when a requested resource is missing

Solution

  1. Step 1: Understand the role of not found exceptions

    Not found exceptions indicate that a requested resource does not exist on the server.
  2. Step 2: Identify the correct response behavior

    Returning a 404 HTTP status code clearly informs the client that the resource is missing.
  3. Final Answer:

    To return a clear 404 status when a requested resource is missing -> Option D
  4. Quick Check:

    Not found exceptions = 404 status [OK]
Hint: Not found means resource missing, so send 404 status [OK]
Common Mistakes:
  • Confusing not found with server errors
  • Thinking it improves database speed
  • Assuming it retries requests automatically
2. Which annotation is used in Spring Boot to mark a custom exception class to return HTTP 404 status automatically?
easy
A. @ResponseStatus(HttpStatus.NOT_FOUND)
B. @ExceptionHandler(HttpStatus.NOT_FOUND)
C. @NotFoundException
D. @HttpStatusCode(404)

Solution

  1. Step 1: Recall Spring Boot annotations for HTTP status

    The @ResponseStatus annotation sets the HTTP status code for exceptions or controller methods.
  2. Step 2: Match the annotation to 404 status

    Using @ResponseStatus(HttpStatus.NOT_FOUND) on a custom exception class sends 404 automatically.
  3. Final Answer:

    @ResponseStatus(HttpStatus.NOT_FOUND) -> Option A
  4. Quick Check:

    @ResponseStatus + NOT_FOUND = 404 [OK]
Hint: Use @ResponseStatus with NOT_FOUND for 404 exceptions [OK]
Common Mistakes:
  • Using @ExceptionHandler instead of @ResponseStatus
  • Assuming @NotFoundException is a valid annotation
  • Using incorrect annotation names
3. Given this controller method in Spring Boot:
 @GetMapping("/items/{id}")
 public Item getItem(@PathVariable Long id) {
     return itemRepository.findById(id)
         .orElseThrow(() -> new ItemNotFoundException(id));
 }

What happens if the item with the given id does not exist?
medium
A. The method returns null and HTTP 200 status
B. An ItemNotFoundException is thrown and HTTP 404 status is returned
C. The server crashes with a NullPointerException
D. The method returns an empty Item object

Solution

  1. Step 1: Analyze the use of orElseThrow

    If the item is not found, orElseThrow triggers the custom ItemNotFoundException.
  2. Step 2: Understand exception handling with @ResponseStatus

    If ItemNotFoundException is annotated with @ResponseStatus(HttpStatus.NOT_FOUND), Spring returns 404 status.
  3. Final Answer:

    An ItemNotFoundException is thrown and HTTP 404 status is returned -> Option B
  4. Quick Check:

    orElseThrow + @ResponseStatus = 404 error [OK]
Hint: orElseThrow triggers exception, annotated exception sends 404 [OK]
Common Mistakes:
  • Assuming null is returned instead of exception
  • Confusing 404 with 500 server error
  • Thinking empty object is returned
4. Consider this code snippet:
 @ResponseStatus(HttpStatus.NOT_FOUND)
 public class ProductNotFoundException extends RuntimeException {
     public ProductNotFoundException(Long id) {
         super("Product " + id + " not found");
     }
 }

 @GetMapping("/products/{id}")
 public Product getProduct(@PathVariable Long id) {
     return productRepo.findById(id).orElseThrow(() -> new ProductNotFoundException(id));
 }

What is the likely problem if the client always receives HTTP 500 instead of 404 when a product is missing?
medium
A. The exception is thrown but Spring does not map it to 404
B. The exception is not annotated with @ResponseStatus
C. The controller method does not handle the exception explicitly
D. The exception class is missing a no-argument constructor

Solution

  1. Step 1: Verify annotation presence

    The exception class is correctly annotated with @ResponseStatus(HttpStatus.NOT_FOUND).
  2. Step 2: Understand Spring's exception mapping

    If Spring returns 500, it means it does not recognize the exception mapping to 404, possibly due to package scanning or configuration issues.
  3. Final Answer:

    The exception is thrown but Spring does not map it to 404 -> Option A
  4. Quick Check:

    Annotated exception but 500 means mapping failed [OK]
Hint: 500 instead of 404 means Spring missed exception mapping [OK]
Common Mistakes:
  • Assuming missing no-arg constructor causes 500
  • Thinking @ResponseStatus is missing when it is present
  • Believing explicit handler is always required
5. You want to create a global exception handler in Spring Boot that returns a JSON error with 404 status and a message when any ResourceNotFoundException occurs. Which approach correctly achieves this?
hard
A. Use @RestController on the exception class and return 404 status
B. Annotate ResourceNotFoundException with @ResponseStatus(HttpStatus.NOT_FOUND) only, no handler needed
C. Create a class annotated with @ControllerAdvice and a method with @ExceptionHandler(ResourceNotFoundException.class) returning ResponseEntity with status 404 and error body
D. Throw ResponseStatusException with 404 inside every controller method manually

Solution

  1. Step 1: Understand global exception handling

    Using @ControllerAdvice with @ExceptionHandler allows centralized handling of exceptions across controllers.
  2. Step 2: Return ResponseEntity with 404 and JSON body

    The handler method can build a ResponseEntity with HttpStatus.NOT_FOUND and a JSON error message for clients.
  3. Final Answer:

    Create a class annotated with @ControllerAdvice and a method with @ExceptionHandler(ResourceNotFoundException.class) returning ResponseEntity with status 404 and error body -> Option C
  4. Quick Check:

    Global handler + ResponseEntity = custom 404 JSON [OK]
Hint: Use @ControllerAdvice + @ExceptionHandler for global JSON 404 [OK]
Common Mistakes:
  • Relying only on @ResponseStatus without custom JSON body
  • Annotating exception class as controller
  • Manually throwing exceptions in every method
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