Try with resources when exception raised in block and close() method on resource rethrows same exception instance
Colm Divilly
colm.divilly at oracle.com
Wed Apr 24 13:50:57 UTC 2024
Hi,
In section 14.20.3.1 of the JLS [1] it is stated:
The meaning of a basic try-with-resources statement of the form:
try ({VariableModifier} R VariableDeclaratorId = Expression ...)
Block
is given by the following translation to a local variable declaration and a try-catch-finally statement:
{
final {VariableModifierNoFinal} R Identifier = Expression;
Throwable #primaryExc = null;
try ResourceSpecification_tail
Block
catch (Throwable #t) {
#primaryExc = #t;
throw #t;
} finally {
if (Identifier != null) {
if (#primaryExc != null) {
try {
Identifier.close();
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
} else {
Identifier.close();
}
}
}
}
I am wondering why the block:
} catch (Throwable #suppressedExc) {
#primaryExc.addSuppressed(#suppressedExc);
}
Does not guard against the possibility that #primaryExc == #suppressedExc?
If #primaryExc == #suppressedExc then addSuppressed will raise an IllegalArgumentException [2]
Whilst unusual for the close method to rethrow the exact same exception instance, I can’t see any reason that this would be prohibited, and so the block should probably look like:
} catch (Throwable #suppressedExc) {
If (#suppressedExc != #primaryExc ) {
#primaryExc.addSuppressed(#suppressedExc);
}
}
Regards,
Colm Divilly
[1]: https://docs.oracle.com/javase/specs/jls/se22/html/jls-14.html#jls-14.20.3.1
[2]: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Throwable.java#L1123
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/jls-jvms-spec-comments/attachments/20240424/d7cb9c52/attachment.htm>
More information about the jls-jvms-spec-comments
mailing list