//
Exception Handling is a mechanism to handle runtime errors (file not found, division by zero, null pointer access) gracefully, without crashing the entire program. It separates error-handling code from normal business logic.
try {
// Code that might throw an exception
int result = 10 / 0;
} catch (ArithmeticException e) {
// Handle the specific exception
System.out.println("Cannot divide by zero: " + e.getMessage());
} catch (Exception e) {
// Catch-all for any other exception
System.out.println("Unexpected error: " + e.getMessage());
} finally {
// ALWAYS executes, whether exception occurred or not
// Used for cleanup: closing files, database connections, etc.
System.out.println("Cleanup complete.");
}
In Java, all exceptions inherit from Throwable:
throws. Compile-time enforcement. Examples: IOException, SQLException.class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds. Short by: $" + amount);
this.amount = amount;
}
public double getAmount() { return amount; }
}
// Usage
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance)
throw new InsufficientFundsException(amount - balance);
balance -= amount;
}
Exception too broadly hides bugs.