Java Reference
In-Depth Information
Creating MyResource. Level = 2
Using MyResource level 2
Using MyResource level 1
Closing MyResource...
When a resource is being closed automatically, an exception may be thrown. If a
try-with-resources
block
completes without throwing an exception and the call to the
close()
method throws the exception, the runtime
reports the exception thrown from the
close()
method. If a
try-with-resources
block throws an exception and the
call to the
close()
method also throws an exception, the runtime suppresses the exception thrown from the
close()
method and reports the exception thrown from the
try-with-resources
block. The following snippet of code
demonstrates this rule:
// Create a resource of MyResource type with two levels, which can throw exception on closing
// and use it thrice so that its use() method throws an exception
try (MyResource mr = new MyResource (2, true) ) {
mr.use();
mr.use();
mr.use(); // Will throw a RuntimeException
}
catch(Exception e) {
System.out.println(e.getMessage());
}
Creating MyResource. Level = 2
Using MyResource level 2
Using MyResource level 1
Low in level.
The third call to the
use()
method throws an exception. In the above snippet of code, the automatic
close()
method call will throw a
RuntimeException
because you pass
true
as the second argument when you create the
resource. The output shows that the
catch
block received the
RuntimeException
that was thrown from the
use()
method, not from the
close()
method.
You can retrieve the suppressed exceptions by using the
getSuppressed()
method of the
Throwable
class. The
method was added in Java 7. It returns an array of
Throwable
objects. Each object in the array represents a suppressed
exception. The following snippet of code demonstrates the use of the
getSuppressed()
method to retrieve the
suppressed exceptions:
try (MyResource mr = new MyResource (2, true) ) {
mr.use();
mr.use();
mr.use(); // Throws an exception
}
catch(Exception e) {
System.out.println(e.getMessage());
// Display messages of supressed exceptions
System.out.println("Suppressed exception messages are...");
for(Throwable t : e.getSuppressed()) {
System.out.println(t.getMessage());
}
}