What is the output of the following application?
package mypkg;/*from w ww .ja v a 2 s. co m*/ import java.io.*; class Exception1 extends Exception { Exception1(String message) { super(message); } } public class Main { public void play() throws Exception1, FileNotFoundException { throw new Exception1("play!"); } public static void main(String... keys) throws Exception1 { final Main p = new Main(); try { p.play(); } catch (Exception e) { throw e; } finally { System.out.println("Done!"); } } }
D.
The play()
method declares two checked exceptions, Exception1 and FileNotFoundException, which are handled in the main()
method's catch block using the Exception type.
The catch block then re-throws the Exception.
The compiler is smart enough to know that only two possible checked exceptions can be thrown here, but they both must be handled or declared.
Since the main()
method only declares one of the two checked exceptions, FileNotFoundException is not handled, and the code does not compile.
For this reason, Option D is the correct answer.
Note that the main()
could have also handled or declared Exception, since both checked exceptions inherit it.
If the main()
method had declared Exception, then Done! would have been printed followed by a stack trace, making Option C the correct answer.