CAP477 · Unit 3: Exceptions and wrappers
Checked, unchecked and custom exceptions
8 practice questions
Key points
- Checked: handle or declare; unchecked: optional
- throw an object, throws in the signature
- Custom exception extends Exception or RuntimeException
- Overrides cannot widen checked exceptions
Checked exceptions (subclasses of Exception but not RuntimeException) must be handled with try/catch or declared with throws; otherwise the compiler reports "unreported exception". Unchecked exceptions (RuntimeException and Error subclasses) need no declaration.
throw vs throws: throw is a statement that throws an exception object (throw new AgeException("negative age", -5);). throws is a clause in the method signature that lists checked exceptions the method may pass to its caller.
Custom exceptions: extend Exception (checked) or RuntimeException (unchecked) and call super(message). They may carry extra data:
class AgeException extends Exception {
int age;
AgeException(String m, int age) { super(m); this.age = age; }
}
Catching it prints negative age -5 in the example.
Exception chaining: new IllegalStateException("wrapped", e) keeps the original as the cause; getCause() returns it (wrapped <- NumberFormatException).
Overriding rule: an overriding method cannot throw a broader checked exception than the overridden one (a method without throws cannot be overridden with throws Exception).
Common library exceptions: List.of(...).add(x) throws UnsupportedOperationException (immutable list); iterator().next() on an empty iterator throws NoSuchElementException.
Catching `Error`: allowed but usually wrong. Catch order Exception then Error is fine as they are unrelated.
Exam pitfall: throw and throws are different keywords; calling a method that declares a checked exception without handling it fails to compile.
Try two questions
AgeException extends Exception with an int age field; check(-5) throws new AgeException("negative age", -5). Printing e.getMessage() + " " + e.age gives:
- negative age 0
- negative age -5
- age -5
- -5 negative age
Show the answer
B. Computed: negative age -5.
List.of(1).add(2) raises:
- No exception; the list grows
- ArrayStoreException
- IllegalStateException
- UnsupportedOperationException
Show the answer
D. List.of creates an immutable list: 'immutable' printed by the catch block.