Exam 1z0-809 All QuestionsBrowse all questions from this exam
Question 14

Given the code fragments:

4. void doStuff() throws ArithmeticException, NumberFormatException, Exception {

5. if (Math.random() >-1 throw new Exception ("Try again");

6. }

and

24. try {

25. doStuff ( ):

26. } catch (ArithmeticException | NumberFormatException | Exception e) {

27. System.out.println (e.getMessage()); }

28. catch (Exception e) {

29. System.out.println (e.getMessage()); }

30. }

Which modification enables the code to print Try again?

    Correct Answer: C

    To enable the code to compile and correctly print 'Try again', you must catch specific exceptions separately and then catch the general Exception class. By replacing line 26 with 'catch (ArithmeticException | NumberFormatException e)', you ensure that any ArithmeticException or NumberFormatException is handled by the first catch block, and the general Exception is handled by the second catch block. This will print 'Try again' when it is thrown from the doStuff method.

Discussion
bnagaraja9099Option: C

Ans: C. If you do A, you still get this exception The exception ArithmeticException is already caught by the alternative Exception

pul26Option: C

Answer is C

InnovationOption: C

C is correct

varconiteOption: C

Answer is C

luzeli25Option: A

A is correct

asdfjhfgjuaDCVOption: C

C is the correct answer. public class Test { static void doStuff() throws ArithmeticException, NumberFormatException, Exception { if (Math.random() > -1) throw new Exception("Try again"); } public static void main(String[] args) { try { doStuff(); } catch (ArithmeticException | NumberFormatException e) { System.out.println(e.getMessage()); } catch (Exception e){ System.out.println(e.getMessage()); } } }

steefaandOption: C

C is correct since Exception classes in multi-catch must be unrelated. Also if superclass and sublass are caught then code must first catch subclass and then superclass.

r1muka5Option: C

Option C is correct despite the fact that the code wouldnt still compile because of error on line 5 (missing closing bracket in the if)

WilsonKKerllOption: B

Option A can't compile Types in multi-catch must be disjoint: 'java.lang.NumberFormatException' is a subclass of 'java.lang.Exception'

WilsonKKerllOption: C

Answer C is better than A. Code is more readable.

mevlt

it is not just because of readability. multi-catch can't have parent and child together. Exception is parent of both ArithmeticException and NumberFormatException.