Java OCA OCP Practice Question 1803

Question

Given the application below, what is the name of the class printed at line e1?

package mypkg;//from w  ww . j  av a  2  s.  co  m
final class Exception1 extends Exception {}
final class Login implements AutoCloseable {
   @Override public void close() throws Exception {
      throw new Exception1();
   }
}
public class Main {
   public final void m() throws Exception {
      try (Login gear = new Login()) {
         throw new RuntimeException();
      }
   }
   public static void main(String... rocks) {
      try {
         new Main().m();
      } catch (Throwable t) {
         System.out.println(t);  // e1
      }
   }
}
  • A. mypkg.Exception1
  • B. java.lang.RuntimeException
  • C. The code does not compile.
  • D. The code compiles, but the answer cannot be determined until runtime.


B.

Note

The code compiles without issue, making Option C incorrect.

In the m() method, two exceptions are thrown.

One is thrown by the close() method and the other by the try block.

The exception thrown in the try block is considered the primary exception and reported to the caller on line e1, while the exception thrown by the close() method is suppressed.

java.lang.RuntimeException is thrown to the main() method.

Option B is the correct answer.




PreviousNext

Related