In this example, w.close() is guaranteed to get called even if the to-function terminates with a Throwable.
In general, if the to-function throws a throwable t1 and the AutoCloseable.close() method throws another
throwable t2, then the throwable t2 gets added to the throwable t1 using t1.addSuppressed(t2).
Encapsulates a
loan(resource) to { ... }
statement.Usage example:
In this example,
w.close()
is guaranteed to get called even if the to-function terminates with a Throwable.In general, if the to-function throws a throwable
t1
and theAutoCloseable.close()
method throws another throwablet2
, then the throwablet2
gets added to the throwablet1
usingt1.addSuppressed(t2)
.the type of the auto-closeable resource.
The Java Language Specification: Java SE 7 Edition: 14.20.3.1 Basic try-with-resources