This week's book giveaway is in the Java in General forum. We're giving away four copies of Helidon Revealed: A Practical Guide to Oracle’s Microservices Framework and have Michael Redlich on-line! See this thread for details.
Chapter 7 (Assertions and Java7 Exceptions) Q&A Self test Question : 10
The answer is marked as D.
Shouldn't this be F : RuntimeException c with suppressed RuntimeException a
If I change the program to display suppressed exceptions as follows -
I get the output -
Supp : java.lang.RuntimeException :a
Exception in thread "main" java.lang.RuntimeException: c
No! The answer and explanation in the book or spot-on.
When you run the program unchanged, you'll get this output:
Exception in thread "main" java.lang.RuntimeException: c
at Animals.run(Animals.java:38)
at Animals.main(Animals.java:32)
And that exactly matches with option D: RuntimeException c with no suppressed exception.
If you would make some small modifications to the code snippet, so you simply could rethrow the exception from the catch block as shown in this code snippet:
Then you get this output:
Exception in thread "main" java.io.IOException
at AnimalsForum.run(Animals.java:14)
at AnimalsForum.main(Animals.java:10)
Suppressed: java.lang.RuntimeException: a
at AnimalsForum$Lamb.close(Animals.java:6)
at AnimalsForum.run(Animals.java:15)
... 1 more
And this output matches exactly with option A (not F): IOException with suppressed RuntimeException a
The explanation in the book explains this perfectly: the exception caught by the catch block matches A (an IOException with a suppressed RuntimeException a), but this exception is completely ignored. The catch block just throws a (new) RuntimeException c (with no suppressed exceptions).
Hope it makes some sense and clears your doubt!
Kind regards,
Roel