I have come across a troubling situation where I expect Java to complain (via an IllegalArgumentException
from Throwable.addSuppressed
) about throwing the same exception twice, once from within a try-with-resources block and once from the AutoCloseable
class's close() routine. I have created a simple test case below which highlights the problem.
I am running JDK 1.7.0_65 with the following code:
public class TestDoubleThrow {
public static void main(String[] args) {
class TestA implements AutoCloseable {
RuntimeException e;
public TestA(RuntimeException e) { this.e = e; }
@Override public void close() { throw e; }
}
RuntimeException e = new RuntimeException("My Exception");
try (TestA A = new TestA(e)) {
throw e;
}
}
}
When I compile and run the code above via the command line I get the expected result, an error indicating I have tried to self-suppress and exception:
[coreys terminal]$ java TestDoubleThrow.java ; java TestDoubleThrow
Exception in thread "main" java.lang.IllegalArgumentException: Self-suppression not permitted
at java.lang.Throwable.addSuppressed(Throwable.java:1043)
at TestDoubleThrow.main(TestDoubleThrow.java:12)
Caused by: java.lang.RuntimeException: My Exception
at TestDoubleThrow.main(TestDoubleThrow.java:9)
However, when I build and run the same code from Eclipse I do not get the same result, I get the following:
Exception in thread "main" java.lang.RuntimeException: My Exception
at TestDoubleThrow.main(TestDoubleThrow.java:9)
I removed the .class path after building from the command line to ensure that Eclipse rebuilt it. Running from a debugger I noticed that from Eclipse the code never enters java.lang.Throwable.addSuppressed()
.
Interestingly, if I build the class from Eclipse, then run it from the command line I DO NOT SEE the self suppression error. Similarly if I build the class from the command line and run it from Eclipse (without building from Eclipse) then I DO SEE the error. This suggests that it is something funny about how eclipse is building the class.
I would like to know how to ensure Eclipse can build the class in such a way that I do get the error, because for my purposes it is an error and I want to be able to detect it when I build and run from Eclipse.