Friday, October 9, 2015

Exception throws in finally clause

Suppose an IOException occurs and then, when closing the resource, the call to close throws another exception.
Which exception will actually be caught? In Java, an exception thrown in a finally clause discards the previous exception. This sounds inconvenient, and it is. After all, the user is likely to be much more interested in the original exception.
The try-with-resources statement reverses this behavior. When an exception is thrown in a close method of one of the AutoCloseable objects, the original exception gets rethrown, and the exceptions from calling close are caught and attached as
“suppressed” exceptions. When you catch the primary exception, you can retrieve those secondary exceptions by calling the getSuppressed method.

No comments:

Post a Comment