SPRING BOOT EXCEPTION HANDLING

Published: (January 31, 2026 at 04:27 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

1. What is Exception?

Exception = unwanted situation that breaks normal flow of program.

Goal of exception handling

  • Prevent program crash
  • Control the error
  • Provide proper messages

2. Java Exception Hierarchy

Throwable
├── Error
└── Exception
    ├── RuntimeException (Unchecked)
    └── Other Exceptions (Checked)

3. Types of Exception (Java Level)

(A) Checked Exception

  • Checked at compile time
  • Must be handled (try‑catch or throws)
  • Extends Exception (but not RuntimeException)

Examples: IOException, SQLException, ClassNotFoundException, FileNotFoundException, InterruptedException

(B) Unchecked Exception

  • Occur at runtime
  • Handling is optional
  • Extends RuntimeException

Examples: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException, IllegalArgumentException

(C) Error

  • JVM / system‑level problems
  • Normally not handled; creating custom Error is bad practice

Examples: OutOfMemoryError, StackOverflowError

4. Checked vs Unchecked Rule

extends Exception        → Checked Exception
extends RuntimeException → Unchecked Exception
extends Error           → Error (avoid)

5. Extending Other Exceptions

Technically possible, but best practice is to extend only:

  • Exception for checked exceptions
  • RuntimeException for unchecked exceptions

Avoid extending specific exceptions such as NullPointerException, IOException, SQLException, etc.

6. try‑catch vs throws

try‑catch

Handle the exception at the point where it occurs.

try {
    FileReader fr = new FileReader("a.txt");
} catch (IOException e) {
    System.out.println("File error");
}

throws

Delegate responsibility to the caller.

public void readFile() throws IOException {
    FileReader fr = new FileReader("a.txt");
}

Rule: Checked exceptions must be either caught or declared with throws.

7. throw vs throws

  • throw – manually throw an exception.
throw new IOException("File not found");
  • throws – declare that a method may throw an exception.
public void read() throws IOException { }

8. Common Exception Meanings

  • ClassNotFoundException – class not found at runtime.
  • FileNotFoundException – file missing or incorrect path.
  • IOException – problems with file, network, or streams.
  • SQLException – SQL database errors (MySQL, PostgreSQL, Oracle). Not used with MongoDB.
  • MongoDB equivalents: MongoException, DuplicateKeyException.
  • InterruptedException – thread was interrupted during sleep, wait, or join.

9. Custom Exceptions

Checked Custom Exception

class MyCheckedException extends Exception {
}

Unchecked Custom Exception

class MyUncheckedException extends RuntimeException {
}

10. Java vs Spring Boot Exception Handling

Java level

  • try‑catch
  • throws
  • Method‑level handling

Spring Boot level

  • Controller/API‑level handling
  • Return JSON responses to clients
  • Annotations: @ExceptionHandler, @ControllerAdvice / @RestControllerAdvice

11. Spring Boot Exception Handling Example

Custom Exception

class UserNotFoundException extends RuntimeException {
    public UserNotFoundException(String msg) {
        super(msg);
    }
}

Global Handler

@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity handle(UserNotFoundException e) {
        return ResponseEntity.status(404).body(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleAll(Exception e) {
        return ResponseEntity.status(500).body("Server Error");
    }
}

Controller

@GetMapping("/user/{id}")
public User getUser(@PathVariable int id) {
    return repo.findById(id)
               .orElseThrow(() -> new UserNotFoundException("User not found"));
}

12. Key Interview Points

  • Checked exception: compile‑time, must be handled.
  • Unchecked exception: runtime, handling optional.
  • SQLException applies only to relational databases, not MongoDB.
  • Custom exception: extend Exception for checked, RuntimeException for unchecked.
  • Spring Boot uses @ControllerAdvice (or @RestControllerAdvice) to handle API errors globally.

13. Summary

TypeExtendHandle
CheckedExceptiontry‑catch or throws
UncheckedRuntimeExceptionOptional
ErrorError (avoid)Avoid handling
Back to Blog

Related posts

Read more »

Day-3 details of Class and Object

Class - Class is a Java keyword - Class is a template - Class is a logical entity - First letter of the class name should be capital CamelCase, e.g., SalaryAcc...