Java SE 8 Programmer II - Exam 1Z0-809 | Question Solution

Given Code Modification for Printing "Try again"

Question

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?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

C.

The given code fragments contain a method doStuff() which declares that it may throw three checked exceptions - ArithmeticException, NumberFormatException, and Exception. In addition, the method contains a condition that randomly throws an exception of type Exception with the message "Try again".

In the try block, the doStuff() method is invoked, and the exceptions thrown by it are caught in the subsequent catch block. However, the catch block does not differentiate between the three declared exceptions, and instead uses a multi-catch block to catch all types of exceptions (including Exception) in a single catch block.

Now, in order to enable the code to print the message "Try again", we need to modify the catch block so that it catches the specific exception that is thrown in the doStuff() method.

Option A - Comment the lines 28, 29, and 30: This option will simply suppress the output of any exception messages, and will not enable the code to print "Try again".

Option B - Replace line 26 with: } catch (Exception | ArithmeticException | NumberFormatException e) { This option uses a multi-catch block that catches all three types of exceptions declared by doStuff(). However, since the Exception type is listed first, it will catch the "Try again" exception and print its message.

Option C - Replace line 26 with: } catch (ArithmeticException | NumberFormatException e) { This option removes the Exception type from the catch block, so the "Try again" exception will not be caught. Therefore, this option will not enable the code to print "Try again".

Option D - Replace line 27 with: throw e; This option will simply rethrow the caught exception, and will not enable the code to print "Try again".

Therefore, the correct answer is B - Replace line 26 with: } catch (Exception | ArithmeticException | NumberFormatException e) {.