Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw runtime exception in Closable.close()

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?

like image 492
kukis Avatar asked Oct 27 '15 19:10

kukis


1 Answers

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).

like image 197
Zoran Regvart Avatar answered Oct 18 '22 01:10

Zoran Regvart