From colm.divilly at oracle.com Wed Apr 24 13:50:57 2024 From: colm.divilly at oracle.com (Colm Divilly) Date: Wed, 24 Apr 2024 13:50:57 -0000 Subject: Try with resources when exception raised in block and close() method on resource rethrows same exception instance Message-ID: 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: