Throw runtime exception in Closable.close()
Asked Answered
P

1

6

During my studies to the OCPJP8 I've encountered one question which doesn't have very clear answer to me. Consider 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 correct answer for a question "Which exception will the code throw?" is "Runtime exception c with no suppressed exception". I have check this code in Eclipse and system.out suggest that the book is right. However, I've also modified the code a bit and added the following system.out just before throwing RuntimeException "c"

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

and the output I've got from this system.out is:

[Ljava.lang.Throwable;@75da931b

So clearly there is a suppressed exception. In debug mode, I've also found that this suppressed exception is the one frown in close() method.

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

Passageway answered 27/10, 2015 at 19:24 Comment(1)
As a side note, use System.out.println(Arrays.toString(e.getSuppressed())); to get a more meaningful output…Dorie
Z
3

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

So when the RuntimeException-C is printed from the main it has no mention of the IOException or the suppressed RuntimeException-A.

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

Zeitgeist answered 27/10, 2015 at 23:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.