Exclude runtime exception in Closable.close ()

While studying at OCPJP8, I came across one question that does not have a clear answer to me. Consider the following code:

public class Animals { class Lamb implements Closeable { public void close() { throw new RuntimeException("a"); } } public static void main(String[] args) { new Animals().run(); } public void run() { try (Lamb l = new Lamb();) { throw new IOException(); } catch (Exception e) { throw new RuntimeException("c"); } } } 

According to the book, the correct answer to the question "What exception will the code make?" "runtime exception c without exception." I checked this code in Eclipse and system.out to make sure the book is correct. However, I also changed the code a bit and added the following system.out just before throwing RuntimeException "c"

  System.out.println(e.getSuppressed().toString()); 

and the output obtained from this .out system:

[Ljava.lang.Throwable; @ 75da931b

So it is clear that there is an excluded exception. In debug mode, I also found that this thrown exception is the one who frowns in the close () method.

Two questions: 1. Why is there no information in the console about the exception caused by the close () method? 2. Is the answer in the book correct?

+6
source share
1 answer

The suppressed exception ( RuntimeException -A) was added to the IOException detected in catch and was lost from the stack trace listing because it was not passed as cause RuntimeException -C.

So, when RuntimeException -C is printed with main , it does not mention an IOException or a suppressed RuntimeException -A.

And therefore, the answer to the book is correct, because the only exception that is propagated from the main method is RuntimeException -C without cause ( IOException ) and without any exceptions thrown (as it was on IOException ).

+3
source

All Articles