Hackforge Academy

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";
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community