Multiple choice

public class ExceptionTest 
{ 
    class TestException extends Exception {} 
    public void runTest() throws TestException {} 
    public void test() /* Point X */ 
    { 
        runTest(); 
    } 
}

At Point X in line 5, which code is necessary to make the code compile?

  1. no code is necessary

  2. throws Exception

  3. catch ( Exception e )

  4. throws RuntimeException

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

Option 2 is correct. This works because it DOES throw an exception if an error occurs. Option 1 is wrong. If you compile the code as given the compiler will complain: unreported exception must be caught or declared to be thrown The class extendsException so we are forced to test for exceptions. Option 3 is wrong. The catch statement belongs in a method body not a method specification. Option 4 is wrong. TestException is a subclass of Exception therefore the test method, in this example, must throw TestException or some other class further up theException tree. Throwing RuntimeException is just not on as this belongs in thejava.lang.RuntimeException branch (it is not a superclass of TestException). The compiler complains with the same error as in A above.