Exception Handling
Exception Handling
Alan Biju
@itsmeambro
Exception Handling
1. Exception Handling in Java
Exception handling is a critical concept in Java and Spring Boot
applications to ensure robust and maintainable code.
Types of Exceptions
Alan Biju
02 @itsmeambro
2. Exception Handling in Spring Boot
Spring Boot provides a centralized way to handle exceptions using
the @ExceptionHandler, @ControllerAdvice, and
ResponseEntityExceptionHandler.
1️⃣ Using @ExceptionHandler (Local Handling)
You can use @ExceptionHandler in a controller to handle specific
exceptions.
@RestController
@RequestMapping("/api")
public class UserController {
@GetMapping("/user/{id}")
public User getUser(@PathVariable int id) {
if (id <= 0) {
throw new UserNotFoundException("User not found with
ID: " + id);
}
return new User(id, "John Doe");
}
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String>
handleUserNotFoundException(UserNotFoundException ex) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
}
2️⃣ Using @ControllerAdvice (Global Exception Handling)
Instead of handling exceptions inside individual controllers, we can create
a global handler.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String>
handleUserNotFoundException(UserNotFoundException ex) {
Alan Biju
03 @itsmeambro
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception
ex) {
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred: " + ex.getMessage());
}
}
3️⃣ Using ResponseEntityExceptionHandler for Standard Responses
Extending ResponseEntityExceptionHandler provides more control.
@RestControllerAdvice
public class CustomExceptionHandler extends
ResponseEntityExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
protected ResponseEntity<Object> handleUserNotFoundException(
UserNotFoundException ex,
WebRequest request) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", new Date());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
}
}
Alan Biju
04 @itsmeambro
📌 Exception Handling Best Practices
✅ Use specific exceptions instead of Exception
✅ Provide meaningful messages for debugging
✅ Never swallow exceptions (log or handle them)
✅ Use finally or try-with-resources for cleanup
✅ Avoid logging + throwing the same exception
✅ Use @ControllerAdvice for centralized exception handling.
✅ Use meaningful HTTP status codes (404 NOT FOUND, 400 BAD
REQUEST).
✅ Avoid exposing sensitive details in error messages.
✅ Use custom exceptions for clarity (UserNotFoundException,
InvalidRequestException).
✅ Log exceptions properly (logger.error("Error Message", ex)).
Alan Biju
05 @itsmeambro
If you find this
helpful, like and
share it with your
friends
Alan Biju
@itsmeambro