Exception handling is tested directly in Theory Assignment Q2. Master the Throwable hierarchy, checked vs unchecked exceptions, and try-catch mechanics.
| Type | Cause & Compiler Rule | Examples |
|---|---|---|
| Checked Exception | Caused by external factors (missing file, database offline). Compiler FORCES handling (`try-catch` or `throws`). | `IOException`, `SQLException`, `FileNotFoundException` |
| Unchecked Exception (`RuntimeException`) | Caused by flawed program logic. Compiler does NOT force handling. Should be fixed in code. | `NullPointerException`, `NumberFormatException`, `ArrayIndexOutOfBoundsException` |
| Exception | Scenario Where It Occurs | How to Handle / Prevent |
|---|---|---|
NullPointerException |
Attempting to invoke a method or access an attribute on an uninitialized (`null`) object reference. | Null checks (`if (obj != null)`), using `Optional |
IOException |
Attempting to read/write a file that is missing, locked, or corrupt during I/O operations. | Wrap in `try-catch(IOException e)` block or declare `throws IOException`. |
NumberFormatException |
Attempting to parse an invalid string into a numeric value (e.g. `Integer.parseInt("abc")`). | Input validation, catching `NumberFormatException` and prompting user for valid numbers. |
ArrayIndexOutOfBoundsException |
Accessing an array index less than 0 or greater than or equal to `array.length`. | Check array bounds before access using `index < array.length`. |
throw is used INSIDE a method body to explicitly instantiate and throw an exception object (e.g., throw new IllegalArgumentException();).throws is declared in the METHOD HEADER to notify callers that this method may throw specified checked exceptions (e.g., public void readFile() throws IOException).
Q: Does the finally block execute if an exception occurs inside the try block?
finally block ALWAYS executes, regardless of whether an exception occurred or was caught (used for cleanup resources like closing database connections or files), unless System.exit(0) is called.