What is “self inhibition is not allowed”, and why does javac generate code lead to this error?

This new Java 7 try - with - resources construct is quite good Or at least, it was good until an exception ruined my day

I finally managed to burn it into a repeatable test. It only uses JUnit jmock

@Test
public void testAddSuppressedIssue() throws Exception {
    Mockery mockery = new Mockery();
    final Dependency dependency = mockery.mock(Dependency.class);

    mockery.checking(new Expectations() {{
        allowing(dependency).expectedCall();
        allowing(dependency).close();
    }});

    try (DependencyUser user = new DependencyUser(dependency)) {
        user.doStuff();
    }
}

// A class we're testing.
private static class DependencyUser implements Closeable {
    private final Dependency dependency;

    private DependencyUser(Dependency dependency) {
        this.dependency = dependency;
    }

    public void doStuff() {
        dependency.unexpectedCall(); // bug
    }

    @Override
    public void close() throws IOException {
        dependency.close();
    }
}

// Interface for its dependent component.
private static interface Dependency extends Closeable {
    void expectedCall();
    void unexpectedCall();
}

Running this example, I get:

java.lang.IllegalArgumentException: Self-suppression not permitted
    at java.lang.Throwable.addSuppressed(Throwable.java:1042)
    at com.acme.Java7FeaturesTest.testTryWithResources(Java7FeaturesTest.java:35)

Reading the documentation, they seem to be saying that if you want to add a suppression exception to yourself, it is to trigger this error But I didn't do that. I just tried using a resource block The java compiler then generates what appears to be illegal code, which makes the feature unusable

Of course, when the test passes, there will be no problem When the test fails, an exception occurs So now I have solved the problem that I initially found that I have resumed using try with resources But the next time an exception occurs, I prefer that the exception is expected to fail, not that Java itself has been issued for no good reason

So... Is there any way to get proper error reports here without giving up trial resources?

Solution

It seems that jmock throws the same exception instance from both methods You can copy it without jmock:

public class Test implements Closeable {
    private RuntimeException ex = new RuntimeException();

    public void doStuff() {
        throw ex;
    }

    public void close() {
        throw ex;
    }
}

try (Test t = new test()) {
    t.doStuff();
}

If so, I think it's jmock, not the java compiler

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>