Answers to Self-Study Questions

Test Yourself #1

What is printed for each of the four runs?

  1. d caught Ex1

  2. c caught Ex2
    b caught Ex1

  3. b caught Ex3

  4. a caught Ex4
    execution stops due to uncaught exception Ex1 thrown in main

Test Yourself #2

Question 1:

static void g() throws Ex1, Ex3 {
    try {
        f();
    } catch (Ex1 ex1) {
        System.out.println("Ex1 caught");
    } catch (Ex2 ex2) {
        System.out.println("Ex2 caught");
        throw new Ex1();
    }		
}

Question 2:

Part A:

  1. f(0, X, "hi")
    nothing printed
    an uncaught ArithmeticException is thrown

  2. f(10, X, "")
    prints "in finally clause"
    an uncaught StringIndexOutOfBoundsException is thrown

  3. f(10, X, "bye")
    prints "array error", "in finally clause"
    an uncaught InternalError is thrown

  4. f(10, X, null)
    prints "null ptr", "in finally clause", "after try block"

Part B: Function f doesn't need to have a throws clause that lists the uncaught exceptions that it might throw because only uncaught CHECKED exceptions need to be listed in a method's throws clause. The uncaught exceptions that f might throw are all UNCHECKED exceptions.