OCP Question 47, Explanation

Given:

class Catcher{
    static void calculate(int[] num){
        try{
            System.out.println(num[1] / (num[1] - num[2]));
        } catch(ArithmeticException ae){
            System.err.println("First one caught");
        }
    }
    public static void main(String[] args){
        try{
            int[] arr = {100, 100};
            calculate(arr);
        } catch(IllegalArgumentException iae){
            System.err.println("Second one caught");
        } catch(Exception e){
            System.err.println("Third one caught");
        }
    }
}

What is the result?

A. 0 Done
B. First one caught
Done
C. Second one caught
D. Done
Third one caught
E. Third one caught

 

The correct answer is E.

 

Apparently, the code compiles, so let’s just analyze its logic: calculate() attempts to access the 2nd and 3rd slots in the supplied array and fails miserably because the array is made of only two elements. Therefore, there can be no division, and the method throws an ArrayOutOfBoundsException instead of an ArithmeticException. Being uncaught, the exception propagates up the call stack and gets intercepted in main() by the last catch.

Although the question makes use of the System.err object, which is out of scope of 1Z0-809, there’s hardly a reason to be alarmed as the code’s intentions are clear: it simply works directly with standard error stream.

Now for the fun part. Do you see any line with “Done” in it?.. Now please insert an appropriate LOC so that options A, B and D will make sense, too.

Click here to see one of possible ways to do it.

Place

System.out.println(“Done”);

after the try-catch block in calculate().

Leave Comment

Your email address will not be published.