What is Global Exception Handling in Spring Boot?
Global Exception Handling in Spring Boot is a mechanism used to handle
exceptions centrally across the entire application using annotations like
@ControllerAdvice and @ExceptionHandler.
Instead of writing exception handling logic separately inside every controller, Spring Boot allows developers to manage all exceptions from one centralized class.
In simple words, global exception handling helps applications return clean, consistent, and user-friendly error responses whenever errors occur.
Why Global Exception Handling is Important
In real-world applications, exceptions can occur for many reasons:
- Invalid user input
- Database connection failure
- Null values
- Resource not found
- Authentication failure
- Validation errors
- Internal server issues
Without proper exception handling:
- Applications may crash unexpectedly
- Users may see confusing technical errors
- Frontend applications may not understand failures
- Sensitive internal details may get exposed
- REST APIs may return inconsistent responses
Global exception handling solves these problems by centralizing error management.
Problems Without Global Exception Handling
Suppose every controller handles exceptions separately:
@RestController
public class StudentController {
@GetMapping("/student/{id}")
public String getStudent(@PathVariable int id) {
try {
if(id != 101) {
throw new RuntimeException("Student Not Found");
}
return "Student Found";
} catch (Exception ex) {
return ex.getMessage();
}
}
}
Issues with This Approach
- Duplicate code in multiple controllers
- Poor maintainability
- Inconsistent error responses
- Difficult debugging
- Hard to scale large applications
Solution: Global Exception Handling
Spring Boot provides:
@ControllerAdvice@ExceptionHandler
These annotations help developers manage exceptions globally from one centralized class.
Main Components of Global Exception Handling
| Component | Purpose |
|---|---|
| @ControllerAdvice | Global exception handling class |
| @ExceptionHandler | Handles specific exceptions |
| @ResponseStatus | Defines HTTP status codes |
| ResponseEntity | Custom API responses |
How Global Exception Handling Works
When an exception occurs:
- Spring Boot detects the exception
- Spring searches for matching exception handlers
- The global handler method executes
- A structured response is returned to the client
Step-by-Step Example of Global Exception Handling
Step 1: Create Custom Exception
public class StudentNotFoundException
extends RuntimeException {
public StudentNotFoundException(String message) {
super(message);
}
}
Step 2: Create Error Response Class
public class ErrorResponse {
private String message;
private int status;
private String timestamp;
public ErrorResponse(
String message,
int status,
String timestamp) {
this.message = message;
this.status = status;
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public int getStatus() {
return status;
}
public String getTimestamp() {
return timestamp;
}
}
Step 3: Create Global Exception Handler
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(StudentNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleStudentException(
StudentNotFoundException ex) {
return new ErrorResponse(
ex.getMessage(),
404,
LocalDateTime.now().toString()
);
}
}
Step 4: Use Exception in Controller
@RestController
public class StudentController {
@GetMapping("/student/{id}")
public String getStudent(@PathVariable int id) {
if(id != 101) {
throw new StudentNotFoundException(
"Student Not Found"
);
}
return "Student Found";
}
}
Output
{
"message": "Student Not Found",
"status": 404,
"timestamp": "2026-05-18T20:10:00"
}
HTTP Response
404 NOT FOUND
Benefits of Global Exception Handling
- Centralized error handling
- Cleaner controller code
- Consistent API responses
- Better maintainability
- Improved frontend integration
- Enhanced application security
- Better debugging and logging
Handling Multiple Exceptions
A single global handler can manage multiple exceptions.
Example
@ExceptionHandler({
ArithmeticException.class,
NullPointerException.class
})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleMultipleExceptions(
Exception ex) {
return new ErrorResponse(
ex.getMessage(),
400,
LocalDateTime.now().toString()
);
}
Handling Generic Exceptions
Developers can also handle all unexpected exceptions globally.
Example
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleGlobalException(
Exception ex) {
return new ErrorResponse(
"Something went wrong",
500,
LocalDateTime.now().toString()
);
}
Real-Time Example in Banking Application
Suppose a banking application fetches account details.
If the account does not exist:
@GetMapping("/account/{id}")
public String getAccount(@PathVariable int id) {
if(id != 1001) {
throw new RuntimeException("Account Not Found");
}
return "Account Found";
}
Global Exception Handler
@ControllerAdvice
public class BankingExceptionHandler {
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleException(
RuntimeException ex) {
return new ErrorResponse(
ex.getMessage(),
404,
LocalDateTime.now().toString()
);
}
}
JSON Response
{
"message": "Account Not Found",
"status": 404,
"timestamp": "2026-05-18T20:15:00"
}
Difference Between Local and Global Exception Handling
| Feature | Local Exception Handling | Global Exception Handling |
|---|---|---|
| Scope | Single Controller | Entire Application |
| Code Duplication | High | Low |
| Maintainability | Difficult | Easy |
| Best For | Small applications | Enterprise applications |
Difference Between @ControllerAdvice and @RestControllerAdvice
| Feature | @ControllerAdvice | @RestControllerAdvice |
|---|---|---|
| Main Usage | MVC + REST | REST APIs |
| Includes @ResponseBody | No | Yes |
| Response Type | View or Data | JSON/Data Only |
Using ResponseEntity in Global Exception Handling
Many enterprise applications use ResponseEntity
for better control over responses.
Example
@ExceptionHandler(StudentNotFoundException.class)
public ResponseEntity<ErrorResponse> handleException(
StudentNotFoundException ex) {
ErrorResponse error = new ErrorResponse(
ex.getMessage(),
404,
LocalDateTime.now().toString()
);
return new ResponseEntity<>(
error,
HttpStatus.NOT_FOUND
);
}
Advantages of Using ResponseEntity
- Dynamic HTTP status handling
- Custom response headers
- Flexible response body
- Better API control
Advantages of Global Exception Handling
- Centralized error management
- Improves application maintainability
- Cleaner controllers
- Consistent REST API responses
- Better frontend-backend communication
- Improved application security
- Enterprise-ready architecture
Disadvantages of Global Exception Handling
- Improper configuration may miss exceptions
- Generic handlers can hide root causes
- Large applications may require multiple advice classes
Best Practices for Global Exception Handling
- Use custom exception classes
- Return proper HTTP status codes
- Use structured JSON responses
- Avoid exposing internal exception details
- Use ResponseEntity for advanced APIs
- Log exceptions properly
- Handle validation errors separately
Common HTTP Status Codes Used
| Status Code | Meaning |
|---|---|
| 400 BAD REQUEST | Invalid request data |
| 401 UNAUTHORIZED | Authentication required |
| 403 FORBIDDEN | Access denied |
| 404 NOT FOUND | Resource not found |
| 500 INTERNAL SERVER ERROR | Server error |
Common Interview Questions on Global Exception Handling
What is global exception handling in Spring Boot?
Global exception handling is a centralized mechanism for handling exceptions across the entire Spring Boot application using @ControllerAdvice and @ExceptionHandler.
Why is global exception handling important?
It improves maintainability, consistency, API readability, and application security.
What is the difference between @ControllerAdvice and @RestControllerAdvice?
@RestControllerAdvice automatically includes @ResponseBody and is mainly used for REST APIs.
Can global exception handling return JSON responses?
Yes. Global exception handlers commonly return structured JSON responses.
Why should custom exceptions be used?
Custom exceptions improve code readability, maintainability, and business-specific error handling.
Conclusion
Global exception handling is one of the most important features in Spring Boot for building scalable, maintainable, and production-ready applications.
It centralizes exception management, improves API consistency, provides user-friendly error responses, and reduces duplicate code.
Using @ControllerAdvice, @ExceptionHandler, and ResponseEntity together helps developers build enterprise-grade REST APIs and microservices.
Understanding global exception handling is essential for Spring Boot developers because error handling is a critical part of modern backend application development.