As i understand it, Java 7’s suppressing exceptions feature is an automatic one. In other words, exceptions happening in what used to be a finally block in 6 are automatically suppressed in favor of exception that took place upon resource allocation.
So, in this example things may go wrong with a) opening a resource and b) closing a resource or c) possibly both.
As i understand it, Java 7 will throw exception that took place upon opening, whom we can ask to give us suppressed exceptions, which took place elsewhere.
try (BufferedReader inputReader = Files
.newBufferedReader(Paths.get(new URI(
"file:///Users/me/Desktop/readme.txt")), Charset
.defaultCharset())) {
String inputLine;
while ((inputLine = inputReader.readLine()) != null) {
System.out.println(inputLine);
}
}
The question is .. Can programmer decide what gets suppressed? After all, public addSuppressed() is there.
Please provide an example and use case.
This is not arbitrary—the suppressed exceptions are the ones that would otherwise mask the main exception that caused the
tryblock to fail—and that’s the ones in thefinallyblock. This feature ensures that you get all the exceptions thrown in the whole construct, but the one you catch will be the more important one.You don’t get to choose what gets suppressed. The method is there, for sure, otherwise the whole thing wouldn’t work. If you like, you can write your own exception handling code and use
addSuppressedad libitum.