Custom exception classes help you handle specific errors in your Spring Boot app clearly. They make your code easier to understand and fix.
Custom exception classes in Spring Boot
public class MyCustomException extends RuntimeException { public MyCustomException(String message) { super(message); } }
Custom exceptions usually extend RuntimeException for unchecked exceptions.
Include constructors to pass error messages or causes.
public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } }
public class InvalidInputException extends RuntimeException { public InvalidInputException(String message) { super(message); } public InvalidInputException(String message, Throwable cause) { super(message, cause); } }
This example shows a custom exception UserNotFoundException used in a service. The controller catches it and returns a 404 error with a message.
package com.example.demo.exception; public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } } // Usage in a service class package com.example.demo.service; import com.example.demo.exception.UserNotFoundException; import org.springframework.stereotype.Service; @Service public class UserService { public String findUserById(int id) { if (id != 1) { // pretend only user with id=1 exists throw new UserNotFoundException("User with id " + id + " not found."); } return "User1"; } } // Controller to handle the exception package com.example.demo.controller; import com.example.demo.exception.UserNotFoundException; import com.example.demo.service.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return userService.findUserById(id); } @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } }
Always create meaningful exception names to describe the error clearly.
Use @ExceptionHandler in controllers to handle custom exceptions and send proper HTTP responses.
Custom exceptions improve code readability and error management in Spring Boot apps.
Custom exceptions let you handle specific errors clearly in your app.
They extend RuntimeException and include constructors for messages.
Use @ExceptionHandler to catch and respond to these exceptions in controllers.
Practice
Solution
Step 1: Understand the role of custom exceptions
Custom exceptions help you identify and manage specific error situations clearly in your code.Step 2: Compare with other options
Replacing all exceptions or auto-fixing errors is not the goal; custom exceptions improve clarity and control.Final Answer:
To handle specific error cases clearly and separately in your application -> Option DQuick Check:
Custom exceptions clarify error handling = C [OK]
- Thinking custom exceptions replace all errors
- Believing they fix errors automatically
- Assuming they improve performance directly
Solution
Step 1: Check correct inheritance
Custom exceptions usually extend RuntimeException to avoid mandatory try-catch blocks.Step 2: Verify constructor usage
Providing a constructor that calls super(message) is standard to pass error messages.Final Answer:
public class MyException extends RuntimeException { public MyException(String message) { super(message); } } -> Option AQuick Check:
Extend RuntimeException with constructor = D [OK]
- Using implements instead of extends
- Extending Exception instead of RuntimeException
- Declaring interface instead of class
public class DataNotFoundException extends RuntimeException {
public DataNotFoundException(String message) {
super(message);
}
}What will happen if this exception is thrown in a Spring Boot controller without any handler?
Solution
Step 1: Understand default Spring Boot behavior
Without a handler, Spring Boot treats RuntimeExceptions as server errors and returns HTTP 500.Step 2: Check other options
Ignoring exceptions or auto 404 responses require explicit handling; server crash does not happen.Final Answer:
The application will return a 500 Internal Server Error response -> Option BQuick Check:
Unhandled RuntimeException = HTTP 500 error [OK]
- Assuming automatic 404 response
- Thinking exceptions are ignored
- Believing server crashes on exception
public class InvalidInputException extends RuntimeException {
public InvalidInputException() {
super();
}
public void InvalidInputException(String message) {
super(message);
}
}Solution
Step 1: Check method declarations
The second method has a return type void, so it is not a constructor but a normal method.Step 2: Understand constructor syntax
Constructors must not have a return type; this causes the message constructor to be invalid.Final Answer:
The second method should be a constructor but is declared as void -> Option CQuick Check:
Constructor must not have return type = B [OK]
- Adding void to constructor
- Confusing methods with constructors
- Extending wrong exception class
ResourceMissingException globally in Spring Boot to return a 404 status with a custom message?Solution
Step 1: Use @ControllerAdvice for global handling
This annotation allows centralized exception handling across all controllers.Step 2: Define @ExceptionHandler method for ResourceMissingException
This method can build a ResponseEntity with HTTP 404 and a custom message to send back.Final Answer:
Create a @ControllerAdvice class with a method annotated @ExceptionHandler(ResourceMissingException.class) that returns ResponseEntity with status 404 and message -> Option AQuick Check:
Global handler with @ExceptionHandler = A [OK]
- Catching exceptions in every controller method
- Using wrong HTTP status annotation
- Overriding error page without exception handler
Ready to prove it?
Pass the test and this pattern moves unknown
