SPRING BOOT EXCEPTION HANDLING
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‑catchorthrows) - Extends
Exception(but notRuntimeException)
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
Erroris 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:
Exceptionfor checked exceptionsRuntimeExceptionfor 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 duringsleep,wait, orjoin.
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‑catchthrows- 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.
SQLExceptionapplies only to relational databases, not MongoDB.- Custom exception: extend
Exceptionfor checked,RuntimeExceptionfor unchecked. - Spring Boot uses
@ControllerAdvice(or@RestControllerAdvice) to handle API errors globally.
13. Summary
| Type | Extend | Handle |
|---|---|---|
| Checked | Exception | try‑catch or throws |
| Unchecked | RuntimeException | Optional |
| Error | Error (avoid) | Avoid handling |