Try-Catch-Finally
Exception handling prevents your program from crashing when errors occur. Use try-catch to handle exceptions gracefully.
Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
} finally {
System.out.println("This always runs.");
}
// Multiple catch blocks
try {
String text = null;
text.length(); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Null reference!");
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
}
// Try-with-resources (auto-closeable)
try (Scanner scanner = new Scanner(System.in)) {
String input = scanner.nextLine();
} // scanner is automatically closed Custom Exceptions
Create custom exception classes for application-specific error handling.
Example
// Custom exception
public class InsufficientFundsException extends Exception {
private double amount;
public InsufficientFundsException(double amount) {
super("Insufficient funds. Needed: $" + amount);
this.amount = amount;
}
public double getAmount() { return amount; }
}
// Throwing custom exception
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(amount - balance);
}
balance -= amount;
}
// Catching custom exception
try {
account.withdraw(1000);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
} 