Does Java's try-with-resources catch errors or just exceptions?

AlikElzin-kilaka :

I have some junit tests which create some resources which should also be closed.

One way to implement this logic is using the @Before and @After approach.

What I did was to encapsulate the creation in some utility class to be reused. For example:

class UserCreatorTestUtil implements AutoClosable {
  User create() {...}
  void close() {...}
}

The whole point is for the object to close itself, rather than needing to remember to close it in @After.

The usage should be:

@Test
void test() {
  try (UserCreatorTestUtil userCreatorTestUtil = new UserCreatorTestUtil()) {
    User user = userCreatorTestUtil.create();
    // Do some stuff regarding the user's phone
    Assert.assertEquals("123456789", user.getPhone());
  }
}

The problem is that junit's assert keyword throws an Error - not Exception.

Will the try-with-resource "catch" the Error and invoke the close method?

* Couldn't find the answer in the try-with-resources documentation.

Thilo :

It does not catch anything. But it does finally close all resources.

finally blocks are run even when an Error is thrown.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=425412&siteId=1