| Checked exception | Unchecked exception |
|---|---|
| Checked at compile time | Happens at run time |
| Must be caught or declared with throws | Not forced |
| IOException, SQLException, FileNotFoundException | NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException |
Hierarchy: Throwable → Error (OutOfMemoryError, StackOverflowError — do not catch) and Exception → RuntimeException (unchecked).
try {
int[] arr = new int[3];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index: " + e.getMessage());
} finally {
System.out.println("finally always runs");
}
// try-with-resources closes the reader automatically
try (BufferedReader br = new BufferedReader(new FileReader("a.txt"))) {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
class InsufficientBalanceException extends Exception { // custom checked exception
InsufficientBalanceException(String msg) { super(msg); }
}
Q & A
-
throw vs throws?throw actually throws one exception object inside a method. throws in the method signature declares which checked exceptions the method may throw.
-
final vs finally vs finalize?final: keyword for constants / no override / no inheritance. finally: block that always runs after try-catch. finalize(): old GC hook, deprecated.