1. What is Exception Handling?

  • Exception = an event that disrupts program flow (e.g., divide by zero, null pointer, file not found).
  • Java provides a robust mechanism to handle these errors gracefully instead of crashing.
  • Exceptions are objects (subclasses of Throwable).

👉 Goal: Detect, handle, recover, and continue execution where possible.


2. Exception Hierarchy

  • Throwable ├── Error (serious issues: OutOfMemoryError, StackOverflowError) └── Exception ├── Checked Exceptions (IOException, SQLException) └── Unchecked Exceptions (RuntimeException → NullPointerException, ArithmeticException)

  • Checked Exceptions: Must be handled at compile time (try-catch or throws).
  • Unchecked Exceptions: Occur at runtime, not enforced by compiler.

📌 Rule of Thumb: Checked = recoverable, Unchecked = programmer mistake.


3. Basic Syntax

3.1 try-catch

try {
    int result = 10 / 0;   // risky code
} catch (ArithmeticException e) {
    System.out.println("Error: Division by zero!");
}

3.2 Multiple catch blocks

try {
    String s = null;
    System.out.println(s.length());
} catch (NullPointerException e) {
    System.out.println("Null reference!");
} catch (Exception e) {
    System.out.println("General Exception: " + e);
}

👉 Always order specific → general exceptions, else compile error.


3.3 finally

try {
    int arr[] = {1,2,3};
    System.out.println(arr[5]); // ArrayIndexOutOfBounds
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid index!");
} finally {
    System.out.println("Always executes (cleanup code).");
}

3.4 try-with-resources (Java 7+)

For auto-closing resources like files, DB connections:

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    System.out.println(br.readLine());
} catch (IOException e) {
    e.printStackTrace();
}

4. throw vs throws

throw (used to actually throw an exception):

throw new IllegalArgumentException("Invalid input!");

throws (used in method signature to declare exception):

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

5. Custom Exceptions

Create your own exception class:

class InvalidAgeException extends Exception {
    InvalidAgeException(String msg) { super(msg); }
}

class Test {
    void validate(int age) throws InvalidAgeException {
        if (age < 18) throw new InvalidAgeException("Not eligible to vote");
    }
}

6. Common Built-in Exceptions

  • NullPointerException → accessing null reference
  • ArithmeticException → divide by zero
  • ArrayIndexOutOfBoundsException → invalid array index
  • NumberFormatException → invalid type conversion
  • IOException → file/stream issues
  • SQLException → database errors

📌 Interview Tip: Always be able to explain which are checked vs unchecked.


7. Best Practices

✔ Catch only specific exceptions, not Exception blindly.
✔ Use finally or try-with-resources for cleanup.
✔ Don’t suppress exceptions silently → log them.
✔ Don’t use exceptions for normal control flow (bad practice).
✔ Wrap lower-level exceptions with meaningful messages.


8. Real-World Usage

  • File Handling → Handle IOException
  • Database Access → Handle SQLException
  • Web Applications → Catch runtime errors to avoid server crash
  • Custom Validation → Throw domain-specific exceptions (e.g., UserNotFoundException)


9. Interview Pitfalls

  • Q: Difference between final, finally, finalize?

    • final → keyword (constant, no override)
    • finally → block in exception handling
    • finalize() → method called before GC (deprecated)
  • Q: Checked vs Unchecked exception?

    • Checked → compile-time (IOException)
    • Unchecked → runtime (NullPointerException)
  • Q: Can finally block override return?

    • Yes, if finally has return, it overrides try/catch return.
    • But this is a bad practice.


Final Summary

  • Exception Handling provides safe error recovery.
  • Master try-catch-finally, throw, throws, try-with-resources.
  • Understand checked vs unchecked.
  • Be ready with examples + interview Q&A.


Next: Chapter 13 Packages & Access Modifiers