Java OCA OCP Practice Question 3066

Question

Given:

public class Main {
   public static void checkIt(int a) {
      if (a == 1)
         throw new IllegalArgumentException();
   }/* www . j a  va2 s  .com*/

   public static void main(String[] args) {
      for (int x = 0; x < 2; x++)
         try {
            System.out.print("t ");
            checkIt(x);
            System.out.print("Here ");
         } finally {
            System.out.print("f ");
         }
   }
}

What is the result?

  • A. "t Here f t "
  • B. "t Here f t f "
  • C. "t Here f t Here f "
  • D. "t Here f t ", followed by an exception.
  • E. "t Here f t f ", followed by an exception.
  • F. "t Here f t Here f ", followed by an exception.
  • G. Compilation fails.


E is correct.

Note

As far as the exception goes, it's thrown during the second iteration of the for loop, and it's uncaught and undeclared (which is legal since it's a runtime exception).

Remember, finally (almost) ALWAYS runs.

In main(), the code is legal: the entire try-finally code is considered a single statement from the for loop's perspective, and of course the idea of a try-finally is legal; a catch statement is not required.




PreviousNext

Related