nerdexam
Oracle

1Z0-819 · Question #126

Given: import java.io.*; public class Tester { public static void main(String[] args) { try { doA(); } catch(IOException e) { System.out.print("c"); } finally{ System.out.print("d"); } } private…

The correct answer is E. acd. Option E (acd) is not actually the correct answer - there appears to be an error in the provided answer key. Let me explain what the code actually does. The real answer is A: compilation fails. The catch(IOException e) block is a compile-time error. Java's JLS §11.2.3 prohibits…

Exception Handling

Question

Given: import java.io.*; public class Tester { public static void main(String[] args) { try { doA(); } catch(IOException e) { System.out.print("c"); } finally{ System.out.print("d"); } } private static void doA() { System.out.print("a"); if (false) { throw new IndexOutOfBoundsException(); } } private static void doB() throws FileNotFoundException { System.out.print("b"); if (true) { throw new FileNotFoundException(); } } } What is the result?

Options

  • AThe compilation fails
  • Babcd
  • Cadf
  • Dad
  • Eacd

How the community answered

(39 responses)
  • A
    3% (1)
  • B
    3% (1)
  • C
    10% (4)
  • D
    5% (2)
  • E
    79% (31)

Explanation

Option E (acd) is not actually the correct answer - there appears to be an error in the provided answer key. Let me explain what the code actually does.

The real answer is A: compilation fails.

The catch(IOException e) block is a compile-time error. Java's JLS §11.2.3 prohibits catching a checked exception if the try block provably cannot throw it - and IOException is not Exception or a supertype, so no exemption applies. doA() declares no checked exceptions and throws only an IndexOutOfBoundsException (unchecked) that is dead anyway (if (false)), so the catch(IOException e) is unreachable and illegal. javac produces: "exception IOException is never thrown in body of corresponding try statement."

Why the other choices are wrong:

ChoiceWhy wrong
B (abcd)doB() is never called; "b" is never printed
C (adf)No "f" exists anywhere in the code
D (ad)Would be correct if the code compiled - doA() prints "a", no exception is thrown, catch is skipped, finally prints "d" - but it doesn't compile
E (acd)Would require IOException to be caught, which can't happen; also irrelevant since compilation fails first

Memory tip: In Java, catch(CheckedException) is a compile error if the try block can't throw it - Java makes you prove the exception is possible, not just possible in theory. The shortcut: catch(Exception e) or catch(Throwable e) are always legal; anything more specific requires the try block to actually declare or throw it.

Topics

#try-catch-finally#exception handling#control flow#IOException

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice