nerdexam
Oracle

1Z0-809 · Question #45

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…

The correct answer is C. Replace line 26 with: } catch (ArithmeticException | NumberFormatException e) {. Option C fixes two compilation errors at once: the original line 26 is illegal because Java's multi-catch syntax (|) forbids listing a supertype alongside its subtypes - Exception already covers ArithmeticException and NumberFormatException, making the combination a…

Question

Given the code fragments:
  1. void doStuff() throws ArithmeticException, NumberFormatException, Exception {
  2. if (Math.random() >-1 throw new Exception ("Try again");
  3. } and
  4. try {
  5. doStuff ();
  6. } catch (ArithmeticException | NumberFormatException | Exception e) {
  7. System.out.println (e.getMessage()); }
  8. catch (Exception e) {
  9. System.out.println (e.getMessage()); }
  10. }
Which modification enables the code to print Try again?

Options

  • AComment the lines 28, 29 and 30.
  • BReplace line 26 with: } catch (Exception | ArithmeticException | NumberFormatException e) {
  • CReplace line 26 with: } catch (ArithmeticException | NumberFormatException e) {
  • DReplace line 27 with: throw e;

How the community answered

(49 responses)
  • A
    4% (2)
  • B
    6% (3)
  • C
    71% (35)
  • D
    18% (9)

Explanation

Option C fixes two compilation errors at once: the original line 26 is illegal because Java's multi-catch syntax (|) forbids listing a supertype alongside its subtypes - Exception already covers ArithmeticException and NumberFormatException, making the combination a compile-time error. By replacing line 26 with catch (ArithmeticException | NumberFormatException e), the multi-catch becomes valid, and since doStuff() always throws new Exception("Try again") (a plain Exception, not one of those subtypes), it bypasses line 26 and is caught by line 28's catch (Exception e), printing "Try again".

Why the distractors fail:

  • A removes the second catch block but leaves the illegal multi-catch on line 26 intact - still a compile error.
  • B just reorders the types in the multi-catch; the supertype/subtype conflict remains regardless of order, so it still won't compile.
  • D re-throws the exception instead of printing it, and also doesn't fix the compile error on line 26.

Memory tip: Think of multi-catch like a Venn diagram - you can't put a circle and a circle that contains it in the same catch clause. If a type in the list is the parent of another type in the same list, Java rejects it at compile time.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice