Java OCA OCP Practice Question 1763

Question

How many lines of text does the following program print?

package mypkg;//  www  .j ava2  s  .  c om
class Exception1 extends RuntimeException {}
public class Main {
   public final static void main(String... participants) {
      try {
         if(!"cat".equals("kat")) {
            new Exception1();
         }
      } catch (Exception1 | NullPointerException e) {
         System.out.println("Spelling problem!");
      } catch (Exception e) {
         System.out.println("Unknown Problem!");
      } finally {
         System.out.println("Done!");
      }
   }
}
  • A. One
  • B. Two
  • C. Three
  • D. The code does not compile.


A.

Note

The program compiles without issue, so Option D is incorrect.

The narrower Exception1 and NullPointerException, which inherit from Exception, are correctly presented in the first catch block, with the broader Exception being in the second catch block.

The if-then statement evaluates to true, and a new Exception1 instance is created, but it is not thrown because it is missing the throw keyword.

For this reason, the try block ends without any of the catch blocks being executed.

The finally block is then called, making it the only section of code in the program that prints a line of text.

For this reason, Option A is the correct answer.




PreviousNext

Related