Paul King created GROOVY-12768:
----------------------------------
Summary: try-with-resources and withCloseable throw
"Self-suppression not permitted" when close() rethrows the block's exception
Key: GROOVY-12768
URL: https://issues.apache.org/jira/browse/GROOVY-12768
Project: Groovy
Issue Type: Bug
Reporter: Paul King
When the block of a try-with-resources statement, or the closure passed to
{{withCloseable}}, throws an exception and the resource's {{close()}} throws
the same instance, Groovy throws {{IllegalArgumentException: Self-suppression
not permitted}} and the original exception is lost.
{code:groovy}
def shared = new IllegalStateException('shared')
def res = { -> throw shared } as AutoCloseable
try (def r = res) { throw shared } // IllegalArgumentException:
Self-suppression not permitted
res.withCloseable { throw shared } // IllegalArgumentException:
Self-suppression not permitted
{code}
The same happens under {{@CompileStatic}}, and for {{withCloseable}} on a
{{Closeable}}. Seen on 3.0.25, 4.0.33, 5.1.3, 6.0.0 and master.
A realistic way to hit it: a resource whose {{close()}} reports a failure it
has already seen. In 6.0, {{AsyncScope.close()}} rethrows a failed child task's
exception, so a block that awaits that child and lets the exception escape
fails this way:
{code:groovy}
import groovy.concurrent.AsyncScope
try (def scope = AsyncScope.create()) {
def child = scope.async { throw new IOException('boom') }
await child // IOException escapes the block; scope.close() rethrows the
same instance
}
{code}
Cause: {{TryWithResourcesASTTransformation}} generates
{{#primaryException.addSuppressed(#suppressedException)}} in the catch around
{{close()}}, as javac does, and {{IOGroovyMethods.withCloseable}} (both
overloads) calls {{thrown.addSuppressed(suppressed)}}.
{{Throwable.addSuppressed}} rejects the exception itself.
Expected: the block's exception is thrown, with nothing suppressed into itself.
Proposed fix: skip {{addSuppressed}} when the close failure is the same
instance as the primary exception: an identity check ({{!==}}, via
{{GeneralUtils.notIdenticalX}}) in the generated code and in both
{{withCloseable}} overloads. {{AsyncScope.withScope}} already does this.
Compatibility: Java's try-with-resources has the same behaviour, and the JLS
translation calls {{addSuppressed}} unconditionally, so this is a deliberate
difference from Java. The only observable change is that the original exception
is thrown rather than an {{IllegalArgumentException}}. The try-with-resources
documentation should mention it.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)