Java OCA OCP Practice Question 2430

Question

What's the output of the following code?

class DB implements AutoCloseable {
    DB() {/*  w  w  w .  j  a v  a2 s.c o m*/
        throw new RuntimeException();
    }
    public void close() throws Exception {
        System.out.println("close");
        throw new Exception();
    }
}
public class Main{
    public static void main(String args[]) {
        try (DB box = new DB()) {
            box.close();
        }
        catch (Exception e) {
            System.out.println("catch:"+e);
        }
        finally {
            System.out.println("finally");
        }
    }
}
a  catch:java.lang.RuntimeException
   close/*from  ww  w  . j  a v  a 2s . c o m*/
   finally

b  catch:java.lang.RuntimeException
   finally

c  catch:java.lang.RuntimeException
   close

d  close
   finally

e  Compilation exception


b

Note

The constructor of class DB throws a RuntimeException, and so the box variable isn't initialized in the try-with-resources statement.

Method close() of class DB isn't called implicitly because execution didn't proceed inside the try block.

When try-with-resources throws an exception, the control is transferred to the catch block.

In this case, the exception handler prints catch:java.lang.RuntimeException.

The finally block always executes, thereafter printing finally.




PreviousNext

Related