Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Java Exception Handling

Exception Hierarchy

All exceptions in Java inherit from Throwable. The two main branches are Error (JVM-level, unrecoverable) and Exception (application-level, recoverable).

Exception Hierarchy
Throwable
├── Error          (OutOfMemoryError, StackOverflowError — don't catch these)
└── Exception
    ├── IOException, SQLException, ...  (checked — must handle or declare)
    └── RuntimeException
        ├── NullPointerException
        ├── ArrayIndexOutOfBoundsException
        ├── ClassCastException
        ├── ArithmeticException
        └── IllegalArgumentException
try-catch-finally & Multi-catch
public class ExceptionDemo {
    public static void main(String[] args) {
        // Basic try-catch-finally
        try {
            int result = 10 / 0;  // ArithmeticException
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Caught: " + e.getMessage());  // / by zero
        } finally {
            System.out.println("finally always runs");
        }

        // Multi-catch (Java 7+) — handle multiple exceptions in one block
        String[] arr = {"10", "abc", null};
        for (String s : arr) {
            try {
                int n = Integer.parseInt(s);
                System.out.println("Parsed: " + n);
            } catch (NumberFormatException | NullPointerException e) {
                System.out.println("Error parsing '" + s + "': " + e.getClass().getSimpleName());
            }
        }

        // throws — declare checked exceptions
        try {
            readFile("missing.txt");
        } catch (java.io.IOException e) {
            System.out.println("File error: " + e.getMessage());
        }
    }

    // throws declares that this method may throw a checked exception
    static void readFile(String path) throws java.io.IOException {
        throw new java.io.IOException("File not found: " + path);
    }
}

Custom Exceptions & try-with-resources

Custom Exception & try-with-resources
import java.io.*;

// Custom checked exception
class InsufficientFundsException extends Exception {
    private double amount;

    public InsufficientFundsException(double amount) {
        super("Insufficient funds. Shortfall: $" + amount);
        this.amount = amount;
    }

    public double getAmount() { return amount; }
}

public class CustomException {

    static void withdraw(double balance, double amount)
            throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount - balance);
        }
        System.out.printf("Withdrew $%.2f. Remaining: $%.2f%n",
                          amount, balance - amount);
    }

    public static void main(String[] args) {
        // Custom exception
        try {
            withdraw(100.0, 150.0);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage());
            System.out.printf("You need $%.2f more.%n", e.getAmount());
        }

        // try-with-resources (Java 7+) — auto-closes resources
        // The resource must implement AutoCloseable
        try (BufferedReader br = new BufferedReader(new StringReader("line1\nline2"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // br is automatically closed here — no finally needed
    }
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.