Hackforge Academy

Category: java

Why Exception Handling?

Published on 24 Jul 2026

Explanation

Exception handling prevents applications from crashing when unexpected errors occur. Instead of returning stack traces to clients, Spring Boot allows you to send meaningful HTTP status codes and user-friendly error messages.

Code:

@GetMapping("/{id}")
public Student getStudent(@PathVariable Long id) {
    return studentService.findById(id);
}

Explanation

A custom exception represents a specific business error, such as a missing resource. Creating dedicated exception classes makes the application easier to understand and allows different errors to be handled appropriately.

Code:

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}

Explanation

The @RestControllerAdvice annotation provides centralized exception handling for all REST controllers. It eliminates duplicate try-catch blocks and ensures consistent error responses throughout the application.

Code:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleException(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(ex.getMessage());
    }
}

Explanation

Instead of returning plain text messages, create a custom error response object containing useful information such as timestamp, status code, error message, and request path. This provides a consistent API response format.

Code:

public class ErrorResponse {
    private LocalDateTime timestamp;
    private int status;
    private String message;
    private String path;
}

Explanation

Services should throw custom exceptions when business rules fail. The global exception handler catches these exceptions and automatically returns the appropriate HTTP response without additional controller code.

Code:

public Student findById(Long id) {
    return repository.findById(id)
        .orElseThrow(() -> new ResourceNotFoundException("Student not 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