What is the result of compiling and running the following application?
package mypkg; //w ww. j a v a 2 s .com class Exception1 extends Exception {} public class Main { public void m() throws Exception { // r1 try { throw new Exception("This Exception"); } catch (RuntimeException e) { throw new Exception1(); // r2 } finally { throw new RuntimeException("Or maybe this one"); } } public static void main(String[] moat) throws Exception { new Main().m(); // r3 } }
D.
The m()
is capable of throwing a variety of exceptions, including checked Exception and Exception1 as well as an unchecked RuntimeException.
All of these are handled by the fact that the method declares the checked Exception class in the method signature, which all the exceptions within the class inherit.
The m()
method compiles without issue.
The call to m()
in the main()
method also compiles without issue because the main()
method declares Exception in its signature.
The code compiles but a stack trace is printed at runtime, making Option D the correct answer.
In case you are wondering, the caller would see RuntimeException: Or maybe this one in the stack trace at runtime, since the exception in the finally block replaces the one from the try block.
The exception in the catch block is never reached because the RuntimeException type declared in the catch block does not handle Exception.