I ran into an alarming situation when I expect Java to complain (via IllegalArgumentException from Throwable.addSuppressed ) about throwing the same exception twice, once from the try-with-resources block and once from the AutoCloseable class close () . I created a simple test case below which the problem is highlighted.
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 through the command line, I get the expected result, an error indicating that I was trying to self-suppress and throw an 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 create 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 the build from the command line to make sure that Eclipse rebuilt it. Running from the debugger, I noticed that from Eclipse the code never goes into java.lang.Throwable.addSuppressed() .
Interestingly, if I build a class from Eclipse, run it from the command line, I DO NOT SEE a self-suppression error. Similarly, if I build a class from the command line and run it from Eclipse (without building from Eclipse), then I WILL DIE the error. This suggests that something is funny about how an eclipse creates a class.
I would like to know how to ensure that Eclipse can create the class in such a way as to get an error, because for my purposes it is an error, and I want it to be detectable when I create and run from Eclipse.