Exceptions
1. What Is an Exception? (beginner)
Exception = runtime problem object (JVM throws on crash: divide-by-zero, null, bad index!). Catch it → program survives. Uncaught → crash + stack trace!
Scanner sc = new Scanner(System.in);
try {
System.out.print("enter a/b: ");
int a = sc.nextInt(), b = sc.nextInt();
System.out.println(a / b); // may throw ArithmeticException!
} catch (ArithmeticException e) { // caught!
System.out.println("can't divide by zero!"); // friendly (no crash!)
} catch (InputMismatchException e) {
System.out.println("numbers only!");
} finally {
System.out.println("done!"); // ALWAYS runs (close here!)
}
4. Traps
- Catch specific first,
Exceptionlast (Exceptionfirst = unreachable ERROR!). finallyruns even withreturn(cleanupenne guarantee!).- Try-with-resources (modern!):
try (Scanner sc = new Scanner(...)) { }(auto-close!).
5. Exam Points
- Try-catch-finally program + flow — 7 marks, very frequent.
- Catch order + finally guarantee — 3-5 marks, frequent.