Given the following class, how many lines contain compilation errors?
package move;//from w w w . ja v a2s . c o m interface Printable { void print() throws Exception; } class Rectangle implements Printable { public void print() throws Exception {} } public class Main { static { try (Rectangle r = new Rectangle()) { throws new IllegalArgumentException(); } catch (Exception e) { } catch (IllegalArgumentException e) { } finally { r.print(); } } }
D.
The code does not compile, so Option A is incorrect.
The first compilation error is that Rectangle does not implement AutoCloseable, meaning a try-with-resources statement cannot be used.
Even though Rectangle does implement Printable, an interface that uses the same abstract method signature as AutoCloseable, the JVM requires AutoCloseable be implemented to use try-with-resources.
The second compilation problem is that throws is used instead of throw inside the try block.
Remember that throws is only used in method signatures.
The third compilation issue is that the order of exceptions in the two catch blocks are reversed.
Since Exception will catch all IllegalArgumentException instances, the second catch block is unreachable.
The final compilation error is that the r variable is used in the finally block, which is out of scope.
Remember that the scope of try-with-resources variables ends when the try statement is complete.
For these four reasons, Option D is the correct answer.