⬅ Previous Next ➡

Exception Handling

Exception Handling in Java: Error Types, try-catch-finally, throw/throws, Custom Exceptions, Hierarchy & Multiple Exceptions
  • Exception Handling is used to handle runtime errors so the program does not terminate unexpectedly.
  • An Exception is an abnormal condition that disrupts normal program flow.
  • Java provides keywords: try, catch, finally, throw, throws.

1) Error Types

  • Compile-time Errors: syntax/typing errors found by compiler (e.g., missing semicolon).
  • Runtime Errors: occur while program runs (e.g., divide by zero).
  • Logical Errors: program runs but gives wrong output due to wrong logic.
  • Errors vs Exceptions:
    • Error: serious problem (OutOfMemoryError), usually not handled.
    • Exception: can be handled using try-catch.

2) try-catch-finally Block

  • try: code that may cause exception.
  • catch: handles the exception.
  • finally: always executes (cleanup code), even if exception occurs or not.
class TryCatchFinallyDemo {
    public static void main(String[] args) {
        int a = 10, b = 0;

        try {
            int ans = a / b; // risky
            System.out.println("Ans: " + ans);
        } catch (ArithmeticException e) {
            System.out.println("Error: Cannot divide by zero");
        } finally {
            System.out.println("Finally block executed (cleanup)");
        }
    }
}

3) Handling Multiple Exceptions

  • You can use multiple catch blocks.
  • Order matters: child exception first, then parent exception.
  • Multi-catch uses | to handle multiple exceptions in one catch.
class MultipleCatchDemo {
    public static void main(String[] args) {
        try {
            String s = null;
            System.out.println(s.length()); // NullPointerException

            int[] arr = {10, 20};
            System.out.println(arr[5]);     // ArrayIndexOutOfBoundsException
        } catch (NullPointerException e) {
            System.out.println("Null value found!");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid array index!");
        } catch (Exception e) {
            System.out.println("General exception handled!");
        }
    }
}
class MultiCatchDemo {
    public static void main(String[] args) {
        try {
            int[] arr = {1, 2};
            System.out.println(arr[2]); // ArrayIndexOutOfBoundsException
        } catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
            System.out.println("Handled: " + e.getClass().getSimpleName());
        }
    }
}

4) throw Keyword

  • throw is used to manually throw an exception.
  • Used for validation (example: marks cannot be negative).
class ThrowDemo {
    static void checkMarks(int marks) {
        if (marks < 0) {
            throw new IllegalArgumentException("Marks cannot be negative");
        }
        System.out.println("Marks: " + marks);
    }

    public static void main(String[] args) {
        checkMarks(70);
        // checkMarks(-5); // uncomment to see exception
    }
}

5) throws Keyword

  • throws is used in method signature to declare that method may throw an exception.
  • Caller must handle it using try-catch or declare throws again.
  • Common with checked exceptions like IOException.
import java.io.FileReader;
import java.io.IOException;

class ThrowsDemo {

    static void readFile() throws IOException {
        FileReader fr = new FileReader("data.txt");
        fr.close();
    }

    public static void main(String[] args) {
        try {
            readFile();
            System.out.println("File read success");
        } catch (IOException e) {
            System.out.println("File error: " + e.getMessage());
        }
    }
}

6) Custom Exceptions

  • Create your own exception by extending Exception (checked) or RuntimeException (unchecked).
  • Use when you want custom validation messages.
// Custom checked exception
class InvalidAgeException extends Exception {
    InvalidAgeException(String msg) {
        super(msg);
    }
}

class CustomExceptionDemo {
    static void verifyAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or above");
        }
        System.out.println("Age Verified: " + age);
    }

    public static void main(String[] args) {
        try {
            verifyAge(20);
            // verifyAge(15);
        } catch (InvalidAgeException e) {
            System.out.println("Custom Error: " + e.getMessage());
        }
    }
}

7) Exception Hierarchy (Basic)

  • Throwable is the top class.
  • Two main branches:
    • Error (serious system issues)
    • Exception (recoverable problems)
  • Exception includes:
    • Checked Exceptions: checked by compiler (IOException, SQLException)
    • Unchecked Exceptions: runtime (NullPointerException, ArithmeticException)
// Quick hierarchy view (conceptual)
// Object
//   └── Throwable
//         ├── Error
//         └── Exception
//               ├── RuntimeException (Unchecked)
//               └── IOException / SQLException ... (Checked)
⬅ Previous Next ➡