DEV Community

Er. Bhupendra
Er. Bhupendra

Posted on

SPRING BOOT EXCEPTION HANDLING

# 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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

throws:

  • Caller ko responsibility deta hai
public void readFile() throws IOException {
   FileReader fr = new FileReader("a.txt");
}
Enter fullscreen mode Exit fullscreen mode

Rule:
Checked Exception = try-catch OR throws (one compulsory)


7. throw vs throws

  • throw → manually exception throw karna
  • throws → method signature me likhna
throw new IOException("File not found");
Enter fullscreen mode Exit fullscreen mode
public void read() throws IOException { }
Enter fullscreen mode Exit fullscreen mode

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

class MyCheckedException extends Exception {
}
Enter fullscreen mode Exit fullscreen mode

Unchecked Custom Exception

class MyUncheckedException extends RuntimeException {
}
Enter fullscreen mode Exit fullscreen mode

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

class UserNotFoundException extends RuntimeException {
   public UserNotFoundException(String msg){
      super(msg);
   }
}
Enter fullscreen mode Exit fullscreen mode

Global Handler

@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");
   }
}
Enter fullscreen mode Exit fullscreen mode

Controller

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

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




Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.