nerdexam
Oracle

1Z0-809 · Question #193

Given: class DataConverter { public void copyFlatFilesToTables() { } public void close() throws Exception { // line n1 throw new RuntimeException(); } } and the code fragment: public static void…

The correct answer is B. A compilation error occurs because the try block doesn't have a catch or finally block. There's an issue with the provided answer key - B is not actually correct, and explaining it as-is would give you wrong information for the exam. Here's what's really happening: The real answer is A. DataConverter does not implement java.lang.AutoCloseable (or Closeable)…

Question

Given: class DataConverter { public void copyFlatFilesToTables() { } public void close() throws Exception { // line n1 throw new RuntimeException(); } } and the code fragment: public static void main(String[] args) throws Exception { // line n2 try (DataConverter dc = new DataConverter()) { // line n2 dc.copyFlatFilesToTables(); } } What is the result?

Options

  • AA compilation error occurs at line n2.
  • BA compilation error occurs because the try block doesn't have a catch or finally block.
  • CA compilation error occurs at line n1.
  • DThe program compiles successfully.

How the community answered

(26 responses)
  • A
    15% (4)
  • B
    73% (19)
  • C
    8% (2)
  • D
    4% (1)

Explanation

There's an issue with the provided answer key - B is not actually correct, and explaining it as-is would give you wrong information for the exam. Here's what's really happening:

The real answer is A. DataConverter does not implement java.lang.AutoCloseable (or Closeable). Try-with-resources requires the resource type to explicitly implement AutoCloseable - having a close() method alone is not enough. This causes a compilation error at line n2, where the try-with-resources statement declares dc.

Why each option is actually wrong/right:

  • A (actually correct): The try-with-resources at line n2 fails to compile because DataConverter doesn't implement AutoCloseable. This is the real error.
  • B (stated correct - but wrong): Try-with-resources does not require a catch or finally block. The Java Language Specification explicitly makes them optional ([Catches] [Finally]). This rule applies to a plain try block, not try-with-resources.
  • C (wrong): close() throws Exception is perfectly valid Java syntax - methods can declare throws Exception.
  • D (wrong): The program does not compile, so "compiles successfully" is false.

Memory tip: For try-with-resources, always check two things: (1) does the resource type explicitly implement AutoCloseable? (2) Are any checked exceptions from close() handled? A method with just a close() method is NOT automatically a valid resource - the implements AutoCloseable declaration is mandatory.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice