Java OCA OCP Practice Question 1795

Question

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!");
      }
   }
}
  • A. Done!
  • B. An exception is printed with play! in the stack trace.
  • C. Both of the above
  • D. None of the above


D.

Note

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.




PreviousNext

Related