Error Handling & Exceptions
Robust error handling is essential for reliable software. Proper exception handling prevents crashes, provides meaningful feedback, and helps developers diagnose problems.
Exception Types
+---------------------------------------------------------+
| EXCEPTION HIERARCHY |
+---------------------------------------------------------+
| |
| Throwable |
| โโโ Error (unrecoverable: OutOfMemory, StackOverflow) |
| โโโ Exception |
| โโโ Checked Exceptions (must handle) |
| โ โโโ IOException |
| โ โโโ SQLException |
| โโโ RuntimeException (unchecked) |
| โโโ NullPointerException |
| โโโ ArrayIndexOutOfBoundsException |
| โโโ IllegalArgumentException |
| |
+---------------------------------------------------------+
Try-Catch Best Practices
// BAD: Swallowing exceptions
try {
readFile(path);
} catch (Exception e) {
// silently ignore
}
// GOOD: Handle and log appropriately
try {
readFile(path);
} catch (FileNotFoundException e) {
logger.warn("Config file not found, using defaults: " + path);
return defaultConfig;
} catch (IOException e) {
logger.error("Failed to read config file", e);
throw new ConfigException("Cannot load configuration", e);
}
Custom Exceptions
public class InsufficientFundsException extends Exception {
private final double amount;
private final double balance;
public InsufficientFundsException(double amount, double balance) {
super("Cannot withdraw $" + amount + " with balance $" + balance);
this.amount = amount;
this.balance = balance;
}
public double getAmount() { return amount; }
public double getBalance() { return balance; }
}
Error Handling Principles
- Don't catch exceptions you can't handle โ let them propagate
- Use specific exception types rather than catching
Exception - Include meaningful error messages that help diagnose the problem
- Use try-with-resources to ensure cleanup happens
- Design your API to minimize the need for callers to catch exceptions
Key Takeaways
- Never silently swallow exceptions
- Create custom exceptions for domain-specific errors
- Distinguish between recoverable and unrecoverable errors
- Good error handling makes debugging much easier