What is the output of the following application?
package vortex;/*from w w w. jav a 2s. c o m*/ class Exception1 extends Exception {} class MyClass implements AutoCloseable { int v; public MyClass(int v) {this.v = v;} public void close() throws Exception { System.out.print(v); } } public class Main { public static void main(String[] twelve) { try (MyClass m1 = new MyClass(1); MyClass m2 = new MyClass(2); MyClass m3 = new MyClass(3)) { } catch (Exception1 e) { System.out.print(4); } finally { System.out.print(5); } } }
D.
The close()
method in each of the resources throws an Exception, which must be handled or declared in the main()
method.
The catch block supports Exception1, but it is too narrow to catch Exception.
Since there are no other catch blocks present and the main()
method does not declare Exception, the try-with-resources statement does not compile, and Option D is the correct answer.
If the catch block was modified to handle Exception instead of Exception1, the code would compile without issue and print 3215 at runtime, closing the resources in the reverse order in which they were declared and making Option B the correct answer.