Core Java
16 — Exceptions
Previous: 15 Records & Sealed · Next: 17 Collections
▶️ java pkg1core/core18ExceptionsDemo.java
Hierarchy
1Throwable2├── Error (OutOfMemoryError — don't catch)3└── Exception4 ├── RuntimeException (unchecked: NPE, IAE)5 └── IOException etc. (checked: must handle)try / catch / finally
1try {2 int[] a = new int[2];3 System.out.println(a[5]);4} catch (ArrayIndexOutOfBoundsException e) {5 System.out.println("Caught: " + e.getMessage());6} finally {7 System.out.println("Always runs");8}try-with-resources (Java 7+)
1try (BufferedReader br = Files.newBufferedReader(path)) {2 return br.readLine();3} // br.close() called automaticallyAlways use for files, streams, connections.
throw and throws
1void withdraw(double balance, double amt) throws InsufficientFundsException {2 if (amt > balance) throw new InsufficientFundsException("short " + amt);3}throw— raise exception nowthrows— declare checked exceptions on method
Custom exceptions
1class InsufficientFundsException extends Exception {2 InsufficientFundsException(String msg) { super(msg); }3}Extend Exception for checked, RuntimeException for unchecked.
Best practices
| Do | Don't |
|---|---|
| Catch specific types | catch (Exception e) {} empty |
Chain cause: new X("msg", cause) |
Swallow exceptions |
| Use try-with-resources | Forget to close files |
| Fail fast with clear messages | Use exceptions for normal flow |
Interview drill → 07 Exceptions
Next → 17 Collections
Source named in this chapter
- core18ExceptionsDemopkg1core/core18ExceptionsDemo.java