# Java & Spring Boot Exception Handling Notes
---
## 1. What is Exception?
Exception = unwanted situation that breaks normal flow of program.
Goal of exception handling:
- Program crash na ho
- Error ko control karna
- Proper message dena
---
## 2. Java Exception Hierarchy
Throwable
├── Error
└── Exception
├── RuntimeException (Unchecked)
└── Other Exceptions (Checked)
---
## 3. Types of Exception (Java Level)
### (A) Checked Exception
- Compile time pe check hoti hai
- Handle karna compulsory hai (`try-catch` OR `throws`)
- Extends: `Exception` (but not RuntimeException)
Examples:
- IOException
- SQLException
- ClassNotFoundException
- FileNotFoundException
- InterruptedException
---
### (B) Unchecked Exception
- Runtime pe aati hai
- Handle karna compulsory nahi
- Extends: `RuntimeException`
Examples:
- NullPointerException
- ArithmeticException
- ArrayIndexOutOfBoundsException
- NumberFormatException
- IllegalArgumentException
---
### (C) Error
- JVM / system level problem
- Normally handle nahi karte
- Custom Error banana bad practice
Examples:
- OutOfMemoryError
- StackOverflowError
---
## 4. Checked vs Unchecked Rule
extends Exception → Checked Exception
extends RuntimeException → Unchecked Exception
extends Error → Error (avoid)
---
## 5. Can we extend other exceptions?
Technically YES:
- Can extend IOException, NullPointerException, etc.
But Best Practice:
- Extend only:
- Exception (for checked)
- RuntimeException (for unchecked)
Avoid:
- Extending NullPointerException, IOException, SQLException etc.
---
## 6. try-catch vs throws
### try-catch:
- Exception yahin handle hoti hai
```
java
try {
FileReader fr = new FileReader("a.txt");
} catch (IOException e) {
System.out.println("File error");
}
throws:
- Caller ko responsibility deta hai
java
public void readFile() throws IOException {
FileReader fr = new FileReader("a.txt");
}
Rule:
Checked Exception = try-catch OR throws (one compulsory)
7. throw vs throws
-
throw→ manually exception throw karna -
throws→ method signature me likhna
java
throw new IOException("File not found");
java
public void read() throws IOException { }
8. Common Exception Meaning
ClassNotFoundException
- Jab runtime pe class nahi milti
FileNotFoundException
- Jab file nahi milti / path galat
IOException
- File / network / stream problem
SQLException
- SQL database problem (MySQL, PostgreSQL, Oracle)
Not used in MongoDB.
MongoDB uses:
- MongoException
- DuplicateKeyException
InterruptedException
- Jab thread sleep/wait/join me ho
- Aur interrupt ho jaye
9. Custom Exception
Checked Custom Exception
java
class MyCheckedException extends Exception {
}
Unchecked Custom Exception
java
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
- Client ko JSON response dena
Uses:
- @ExceptionHandler
- @ControllerAdvice / @RestControllerAdvice
11. Spring Boot Exception Handling Example
Custom Exception
java
class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String msg){
super(msg);
}
}
Global Handler
java
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handle(UserNotFoundException e){
return ResponseEntity.status(404).body(e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAll(Exception e){
return ResponseEntity.status(500).body("Server Error");
}
}
Controller
java
@GetMapping("/user/{id}")
public User getUser(@PathVariable int id){
return repo.findById(id)
.orElseThrow(() -> new UserNotFoundException("User not found"));
}
12. Key Interview Lines
- Checked exception = compile time, must handle
- Unchecked exception = runtime, optional handling
- SQLException only for SQL DB, not MongoDB
-
Custom exception:
- extends Exception → checked
- extends RuntimeException → unchecked
Spring Boot handles API errors using @ControllerAdvice
13. Summary
| Type | Extend | Handle |
|---|---|---|
| Checked | Exception | try-catch OR throws |
| Unchecked | RuntimeException | optional |
| Error | Error | avoid |
END
Top comments (0)