Consider a Spring Boot REST controller that throws a custom exception ResourceNotFoundException when a resource is missing. What will the client receive if no global exception handler is defined?
public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } @RestController public class MyController { @GetMapping("/item/{id}") public String getItem(@PathVariable String id) { throw new ResourceNotFoundException("Item not found"); } }
Think about what Spring Boot does by default when an exception is thrown and no handler is present.
Without a global or controller-specific exception handler, Spring Boot treats uncaught exceptions as server errors and returns a 500 status with a default error page.
Choose the correct way to define a custom unchecked exception class named InvalidInputException that accepts a message.
Remember that unchecked exceptions extend RuntimeException.
Custom unchecked exceptions should extend RuntimeException. Option A extends Exception which is checked, C does not extend any class, and D extends Throwable which is not recommended.
Given the following code, why does the handleCustomException method not handle MyCustomException?
public class MyCustomException extends RuntimeException { public MyCustomException(String message) { super(message); } } @RestController public class DemoController { @GetMapping("/test") public String test() { throw new MyCustomException("Error occurred"); } } @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity<String> handleCustomException(IllegalArgumentException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); } }
Check the exception type specified in the @ExceptionHandler annotation.
The handler method is set to catch IllegalArgumentException, but the thrown exception is MyCustomException, so it is not caught.
Given this custom exception and handler, what HTTP status code will the client receive when DataConflictException is thrown?
public class DataConflictException extends RuntimeException { public DataConflictException(String message) { super(message); } } @ControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(DataConflictException.class) public ResponseEntity<String> handleConflict(DataConflictException ex) { return ResponseEntity.status(HttpStatus.CONFLICT).body(ex.getMessage()); } }
Look at the status code used in the ResponseEntity.
The handler returns a ResponseEntity with status HttpStatus.CONFLICT, which corresponds to 409.
Which of the following is the best reason to create custom exception classes in a Spring Boot app?
Think about how custom exceptions improve error handling and client communication.
Custom exceptions allow precise identification of error causes and enable tailored HTTP responses, improving API clarity and client experience.