Exception Handling · Introduction to Java Programming

Exceptions

Watch lectures

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, Exception last (Exception first = unreachable ERROR!).
  • finally runs even with return (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.
Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.

← All Introduction to Java Programming modules