# Exception Handling Best Practices
## 1. Specific Exception Catch karo
```java
// Bad
catch (Exception e) { }
// Good
catch (FileNotFoundException e) { }
catch (IOException e) { }
```
## 2. Empty catch block mat rakho
```java
// Bad
catch (Exception e) { } // Silent failure — bahut bura
// Good
catch (Exception e) {
logger.error("Error occurred: ", e);
throw new RuntimeException("Processing failed", e);
}
```
## 3. Exception Swallow mat karo
```java
// Bad
try { riskyOperation(); }
catch (Exception e) { return false; } // Exception lost!
// Good
try { riskyOperation(); }
catch (Exception e) {
logger.error("riskyOperation failed", e);
return false;
}
```
## 4. Resources close karo — try-with-resources
```java
// Good
try (InputStream is = new FileInputStream("file")) {
// use is
} catch (IOException e) {
e.printStackTrace();
}
```
## 5. Custom Exceptions meaningful banao
```java
// Bad
throw new Exception("Error");
// Good
throw new UserNotFoundException("User not found with id: " + userId);
```
## 6. Checked Exception sirf tab jab caller handle kar sake
Agar caller kuch nahi kar sakta — RuntimeException use karo.
## 7. finally mein exception mat throw karo
Original exception lost ho jaati hai.
## 8. Log karo, phir handle karo
```java
catch (SQLException e) {
logger.error("DB error for user: " + userId, e);
throw new ServiceException("Could not retrieve user", e);
}
```Back to Course