How to Create Custom Exception in Spring Boot Easily
To create a custom exception in Spring Boot, define a new class that extends
RuntimeException or Exception. Then, use @ResponseStatus to set the HTTP status or handle it globally with @ControllerAdvice.Syntax
Define a custom exception class by extending RuntimeException or Exception. Optionally, annotate it with @ResponseStatus to specify the HTTP status code returned when this exception is thrown.
Example parts:
public class MyException extends RuntimeException: creates the custom exception class.- Constructor with message: allows passing error details.
@ResponseStatus(HttpStatus.NOT_FOUND): sets HTTP 404 status for this exception.
java
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } }
Example
This example shows a custom exception ResourceNotFoundException used in a Spring Boot REST controller. When a resource is not found, the exception is thrown and Spring returns a 404 status with the message.
java
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.ResponseStatus; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } @ResponseStatus(HttpStatus.NOT_FOUND) class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } @RestController @RequestMapping("/items") class ItemController { @GetMapping("/{id}") public String getItem(@PathVariable int id) { if (id != 1) { // only id 1 exists throw new ResourceNotFoundException("Item with id " + id + " not found"); } return "Item 1 details"; } }
Output
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"timestamp": "...",
"status": 404,
"error": "Not Found",
"message": "Item with id 2 not found",
"path": "/items/2"
}
Common Pitfalls
- Not extending
RuntimeExceptionorExceptionproperly causes errors. - Forgetting
@ResponseStatusmeans Spring returns 500 error by default. - Throwing checked exceptions without handling leads to compilation errors.
- Not using
@ControllerAdvicefor global handling can cause repetitive code.
java
/* Wrong: does not extend Exception or RuntimeException */ public class BadException { public BadException(String message) {} } /* Right: extends RuntimeException and uses @ResponseStatus */ @ResponseStatus(HttpStatus.BAD_REQUEST) public class BadRequestException extends RuntimeException { public BadRequestException(String message) { super(message); } }
Quick Reference
Summary tips for custom exceptions in Spring Boot:
- Extend
RuntimeExceptionfor unchecked exceptions. - Use
@ResponseStatusto set HTTP status easily. - Use
@ControllerAdvicefor centralized exception handling. - Include constructors with message and cause for flexibility.
Key Takeaways
Create custom exceptions by extending RuntimeException or Exception classes.
Use @ResponseStatus to link exceptions with HTTP status codes.
Throw custom exceptions in your code to signal specific error conditions.
Use @ControllerAdvice for global exception handling to keep controllers clean.
Always provide constructors with error messages for clarity.