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
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)- A15% (4)
- B73% (19)
- C8% (2)
- D4% (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
DataConverterdoesn't implementAutoCloseable. 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 plaintryblock, not try-with-resources. - C (wrong):
close() throws Exceptionis perfectly valid Java syntax - methods can declarethrows 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.