JaJava · Lesson 7 of 9

Exception Handling

Java has checked exceptions, which force you to handle or declare errors. This is either responsible engineering or the most annoying thing in existence, depending on your morning.

Java
import java.io.*;
import java.util.*;

public class ExceptionHandling {
    // Checked exception — must declare or catch it
    public static String readFile(String path) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        }
        return sb.toString();  // auto-closes reader (try-with-resources)
    }

    // Custom exception
    static class InsufficientFundsException extends RuntimeException {
        private final double amount;
        private final double balance;

        InsufficientFundsException(double amount, double balance) {
            super(String.format("Cannot withdraw %.2f, balance is %.2f", amount, balance));
            this.amount = amount;
            this.balance = balance;
        }

        public double getAmount() { return amount; }
        public double getBalance() { return balance; }
    }

    public static void main(String[] args) {
        // try-catch-finally
        try {
            String content = readFile("data.txt");
            System.out.println(content);
        } catch (FileNotFoundException e) {
            System.err.println("File not found: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IO error: " + e.getMessage());
        } finally {
            System.out.println("Always runs");
        }

        // Multi-catch (Java 7+)
        try {
            int[] arr = {1, 2, 3};
            int n = Integer.parseInt("abc");
            System.out.println(arr[n]);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
◆ Note
RuntimeException and its subclasses are unchecked — you don't have to declare or catch them. IOException, SQLException, and similar are checked — you must handle them. Design custom exceptions: extend RuntimeException for unchecked, Exception for checked.