1. University MCA (AI/ML) Semester 2
  2. CAP477
  3. Unit 3

CAP477 · Unit 3: Exceptions and wrappers

Exception handling: try, catch, finally

8 practice questions

Key points

  • Catch specific before general
  • finally runs after return but not after System.exit
  • Error is not an Exception
  • Return in finally overrides

An exception is an event that disrupts normal flow. Java handles it with try { } catch (Type e) { } finally { }.

Hierarchy: Throwable -> Error (JVM problems such as StackOverflowError, OutOfMemoryError; do not catch) and Exception. Exception has checked exceptions (IOException, SQLException) and RuntimeException and its unchecked children (ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, NumberFormatException, IllegalArgumentException).

Flow rules (verified by running):

  • The first matching catch runs; later ones are skipped. Order catches from specific to general: a subclass catch after its superclass catch is a compile error ("has already been caught"). Multi-catch catch (A | B e) is allowed for unrelated types.
  • finally runs whether or not an exception occurred, even after `return`. Exception: it does not run if the JVM exits (System.exit(0)).
  • A return inside finally overrides an earlier return: try { return 1; } finally { return 2; } returns 2 (avoid it). But changing a local variable in finally after return x does not change the already-computed return value.
  • try with return prints: try, finally, then the caller prints 1.
  • In catch ... return s; with finally { s += "c"; print }, the finally prints abc but the method returns the earlier ab value.
  • Nested: inner finally runs before the outer catch (f1, caught inner, f2).

Messages: Integer.parseInt("abc") -> NumberFormatException: For input string: "abc"; dividing integers by zero -> / by zero. StackOverflowError is an Error, not an Exception, so catch (Exception e) does not catch it.

Exam pitfall: a try block needs at least one catch or a finally (or resources).

Try two questions

Question 1 · Tier 1, Recall

Which of these is an unchecked exception?

  1. IOException
  2. SQLException
  3. Exception (the class itself)
  4. ArithmeticException
Show the answer

D. RuntimeException and its subclasses are unchecked.

Question 2 · Tier 4, Analyse

Which statement about StackOverflowError is correct?

  1. It is a subclass of RuntimeException so it is unchecked
  2. It is an Error, so catch (Exception e) does not catch it
  3. It can never be caught by any catch block
  4. It is a checked exception that must be declared
Show the answer

B. Hierarchy check printed: true true false true (Exception, RuntimeException, Error-as-Exception, SOE-as-Error).