โ† Back to Courses
ยฉ 2025 sampathirao yoganandh
Week 11 ยท CO-3

Exception Handling

try/catch/finally, throw, throws, Built-in & User-defined Exceptions  CO-3

What is an Exception?

An exception is an abnormal condition that disrupts the normal flow of a program at runtime. Java provides a robust mechanism to handle such conditions gracefully.

Type of ErrorPhaseExample
Syntax ErrorCompile timeMissing semicolon, wrong keyword
Logical ErrorRuntime (wrong output)Wrong formula used
Runtime ExceptionRuntime (crash)Divide by zero, null pointer

Exception Hierarchy

All exceptions in Java are subclasses of Throwable:

java.lang.Object
  โ””โ”€โ”€ java.lang.Throwable
        โ”œโ”€โ”€ java.lang.Error          (JVM errors โ€” do NOT handle)
        โ”‚     โ”œโ”€โ”€ OutOfMemoryError
        โ”‚     โ”œโ”€โ”€ StackOverflowError
        โ”‚     โ””โ”€โ”€ VirtualMachineError
        โ””โ”€โ”€ java.lang.Exception      (handle these)
              โ”œโ”€โ”€ Checked Exceptions (compile-time)
              โ”‚     โ”œโ”€โ”€ IOException
              โ”‚     โ”œโ”€โ”€ SQLException
              โ”‚     โ””โ”€โ”€ FileNotFoundException
              โ””โ”€โ”€ RuntimeException   (unchecked)
                    โ”œโ”€โ”€ ArithmeticException
                    โ”œโ”€โ”€ NullPointerException
                    โ”œโ”€โ”€ ArrayIndexOutOfBoundsException
                    โ”œโ”€โ”€ ClassCastException
                    โ””โ”€โ”€ NumberFormatException
๐Ÿ’ก Did You KnowChecked exceptions must be handled or declared. Unchecked exceptions (RuntimeException subclasses) are optional to handle. Errors should never be caught.

try-catch-finally

public class ExceptionDemo {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30};

        try {
            int result = arr[0] / 0; // ArithmeticException
            arr[5] = 99;               // ArrayIndexOutOfBoundsException
        } catch (ArithmeticException e) {
            System.out.println("Math error: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array error: " + e.getMessage());
        } finally {
            System.out.println("Finally always executes!");
        }
    }
}
๐Ÿ“Œ Key Pointfinally always executes โ€” even if a return is in the try block, or an exception is thrown that is not caught. It is used to release resources.

throw & throws

KeywordPurposeUsed in
throwManually throw an exception objectInside a method body
throwsDeclare that a method may throw an exceptionMethod signature
// Using 'throw' to manually throw an exception
static void validateAge(int age) {
    if (age < 18)
        throw new IllegalArgumentException("Age must be 18 or above: " + age);
    System.out.println("Valid age: " + age);
}

// Using 'throws' to delegate handling to caller
static void readFile(String path) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    System.out.println(br.readLine());
    br.close();
}

public static void main(String[] args) {
    try {
        validateAge(15);
        readFile("data.txt");
    } catch (IllegalArgumentException | IOException e) {
        System.out.println("Error: " + e.getMessage());
    }
}

Multiple catch Blocks

Multiple catch blocks allow handling different exception types separately. Catch order matters โ€” more specific exceptions must come before general ones.

try {
    String s = null;
    s.length();             // NullPointerException
    int x = Integer.parseInt("abc"); // NumberFormatException
} catch (NullPointerException e) {
    System.out.println("Null: " + e);
} catch (NumberFormatException e) {
    System.out.println("Format: " + e);
} catch (Exception e) {
    // catches any other Exception โ€” must be LAST
    System.out.println("General: " + e);
}
โš ๏ธ ImportantIf a parent exception class (like Exception) appears before a child (like NullPointerException), a compile-time error occurs: 'exception already caught'.

Nested try

try {
    System.out.println("Outer try");
    try {
        int x = 10 / 0;  // handled in inner catch
    } catch (ArithmeticException e) {
        System.out.println("Inner catch: " + e.getMessage());
        throw new RuntimeException("Re-thrown"); // escalate
    }
} catch (RuntimeException e) {
    System.out.println("Outer catch: " + e.getMessage());
}

User-defined Exceptions

Create custom exceptions by extending Exception (checked) or RuntimeException (unchecked).

// Custom checked exception
class InsufficientFundsException extends Exception {
    private double amount;
    InsufficientFundsException(double a) {
        super("Insufficient funds. Need: โ‚น" + a);
        amount = a;
    }
    double getAmount() { return amount; }
}

class BankAccount {
    double balance = 1000;

    void withdraw(double amt) throws InsufficientFundsException {
        if (amt > balance)
            throw new InsufficientFundsException(amt - balance);
        balance -= amt;
    }
}

Common Built-in Exceptions

ExceptionCause
ArithmeticExceptionDivision by zero
NullPointerExceptionAccessing method/field on null reference
ArrayIndexOutOfBoundsExceptionArray index < 0 or >= length
NumberFormatExceptionInvalid string-to-number conversion
ClassCastExceptionInvalid type casting
StackOverflowErrorInfinite recursion
FileNotFoundExceptionFile path does not exist
IOExceptionGeneral I/O failure
StringIndexOutOfBoundsExceptionString index out of range
๐Ÿ“„

Download PDF Notes

Save these notes as a PDF for offline reference

View / Download PDF