RFE to change try-with-resources

Alex Buckley alex.buckley at oracle.com
Wed Feb 16 18:33:14 UTC 2022

We received a suggestion to change the exception thrown by 
try-with-resources in the case when (paraphrasing) a more serious 
exception is thrown from closing a resource than was thrown from the try 


Notably, if the try block throws an Exception but the automatic call to 
close() throws an Error, then _today_ try-with-resources throws the 
Exception (with the Error as a suppressed exception) but _in future_ 
would throw the Error (with the Exception as a suppressed exception).

Because a try-with-resources statement has so many parts that can throw 
-- resource initializers, try block, catch block(s), finally block, and 
resource closers -- there are numerous scenarios where a single 
try-with-resources statement can have different exceptions arising from 
different parts, and we need to choose which exception is the "real" 
reason for terminating the try-with-resources statement. A policy that 
chooses a more-serious exception over a less-serious exception is, 
perhaps, in itself, a good idea -- but such a policy would have to be 
applied consistently in all scenarios, which would significantly change 
the try-with-resources feature.

In any case, it's not a source-compatible change. A try-with-resources 
statement that throws a checked exception today could throw an unchecked 
exception in future, so you would get a compile-time error where the 
rest of the program tries to catch the checked exception.

This RFE is a good example of something that feels like a "small tweak" 
to a much-loved feature, but would actually make the feature harder to 
learn and use -- to say nothing of the compatibility impact of changing 
the feature so long after its introduction (try-with-resources shipped 
in Java 7 after huge amounts of discussion).


More information about the compiler-dev mailing list