Category: spring_boot
Global Exception Handling
Published on 24 Jun 2026
Explanation
Global Exception Handling allows you to
manage exceptions across the entire
application
from a central location. This avoids
writing try-catch blocks in every controller
method and provides consistent error
responses.
Code:
@RestControllerAdvice
public class GlobalExceptionHandler {
}
Explanation
The @ExceptionHandler annotation is used to
catch specific exceptions and return a
custom response. This improves API usability
by providing meaningful error messages.
Code:
@ExceptionHandler(Exception.class)
public ResponseEntity<String>
handleException(Exception ex) {
return ResponseEntity.status(
HttpStatus.INTERNAL_SERVER_ERROR)
.body(ex.getMessage());
}
Explanation
A custom exception can be created
to represent business-specific errors.
For example,
a StudentNotFoundException can be
thrown when
a requested student does not exist.
Code:
public class StudentNotFoundException
extends RuntimeException {
public StudentNotFoundException(
String message) {
super(message);
}
}
Explanation
The global exception handler can catch
custom exceptions and return appropriate
HTTP
status codes such as 404 Not
Found.
Code:
@ExceptionHandler(
StudentNotFoundException.class)
public ResponseEntity<String>
handleStudentNotFound(
StudentNotFoundException ex) {
return ResponseEntity.status(
HttpStatus.NOT_FOUND)
.body(ex.getMessage());
}
Explanation
Controllers can throw exceptions without
handling
them directly. The Global Exception Handler
automatically catches and processes them,
keeping
controller code clean and focused on
business logic.
Code:
@GetMapping("/students/{id}")
public String getStudent(@PathVariable
Long id) {
if (id <= 0) {
throw new
StudentNotFoundException("
Student not found with ID: " + id);
}
return "Student Found";
}