OCP Question 38, Explanation

Given the code fragments:

2. void earn() throws ArithmeticException, NumberFormatException, Exception {
3.     if (Math.random() < 0.1) throw new Exception ("C'mon! You can do better than that.");
4. }

and

14. try {
15.     earn( );
16. } catch(ArithmeticException | NumberFormatException | Exception e) {
17.     System.out.println (e.getMessage()); }
18. catch(Exception e) {
19.     System.out.println (e.getMessage()); }
20. }

Which modification enables the code to print Try again?

A. Comment the lines 18, 19 and 20.
B. Replace line 16 with:

  } catch (Exception | ArithmeticException | NumberFormatException e) {

C. Replace line 16 with:

  } catch (ArithmeticException | NumberFormatException e) {

D. Replace line 17 with:

  throw e;

 

The correct answer is C.

Speaking of exception handling rules, on our OCA exam we applied the CSR. 1Z0-809, however, makes use of one more construct, which is called “multi-catch clause”, together with a couple of new rules associated with it. This particular Problem is built on the fact that the union of types employed as the exception parameter may not contain subtypes (ref.to JLS, §14.20, The try statement; Nailing 1Z0-808 also discusses this aspect in its Problem 8.12).

In our case the multi-catch clause on LOC 16 specifies a union of types made of three classes: ArithmeticException, NumberFormatException and Exception. While AE and NFE are indeed unrelated (both are unchecked exceptions, by the way), they do descend from Exception, thus violating the above-mentioned rule.

So how can we fix this problem? By applying option C, of course! After all, while option B also mentions line 16, it doesn’t solve the issue: the classes are still related even if we re-arrange their positions within the clause.

Another new rule that we should be aware of on our exam is that the exception parameter in multi-catch clauses is at least implicitly final; we’ll meet this trap soon enough.

Leave Comment

Your email address will not be published.