nerdexam
Oracle

1Z0-811 · Question #20

Given the code fragment: public static void main (String[] args) { int[] arr = {10, 0}; int i = 0; try { int answer = arr[i] / arr[i + 1]; } catch (Exception e) { System.out.println ("Unknown…

The correct answer is D. A compilation error occurs. Option D is correct because Java requires catch blocks to be ordered from most specific to most general. Since ArithmeticException is a subclass of Exception, placing catch (Exception e) first makes the catch (ArithmeticException ae) block unreachable - the compiler detects…

Exception Handling and Methods

Question

Given the code fragment: public static void main (String[] args) { int[] arr = {10, 0}; int i = 0; try { int answer = arr[i] / arr[i + 1]; } catch (Exception e) { System.out.println ("Unknown issues."); } catch (ArithmeticException ae) { System.out.println ("Invalid divisor."); } } What is the result?

Options

  • AUnknown issues. Invalid divisor.
  • BUnknown issues.
  • CInvalid divisor.
  • DA compilation error occurs.

How the community answered

(60 responses)
  • A
    5% (3)
  • B
    17% (10)
  • C
    7% (4)
  • D
    72% (43)

Explanation

Option D is correct because Java requires catch blocks to be ordered from most specific to most general. Since ArithmeticException is a subclass of Exception, placing catch (Exception e) first makes the catch (ArithmeticException ae) block unreachable - the compiler detects this and raises a compile-time error before the program ever runs.

Options A and B are wrong because no output is ever produced; the code fails at compilation, not at runtime. Option C is also wrong for the same reason - "Invalid divisor." can never print because execution never begins.

Memory tip: Think "children before parents" in catch blocks. If a parent class (Exception) appears before a child class (ArithmeticException), the child's block is permanently shadowed and the Java compiler won't allow it - unlike some languages, Java enforces this at compile time, not silently.

Topics

#exception handling#catch block ordering#exception hierarchy#compilation error

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice