Skip to content

Instantly share code, notes, and snippets.

@saberduck
Created January 25, 2018 17:14
Show Gist options
  • Save saberduck/5bb8d91fb62614692d010458e62c7073 to your computer and use it in GitHub Desktop.
Save saberduck/5bb8d91fb62614692d010458e62c7073 to your computer and use it in GitHub Desktop.
try-with-resources and suppressed exceptions
public class TryWithResourcesTest {
public static void main(String[] args) throws Exception {
try (MyClosable a = new MyClosable()) {
if (System.currentTimeMillis() % 2 == 0) {
throw new RuntimeException("Exception on try block");
}
} catch (Exception e) {
Throwable[] suppressed = e.getSuppressed();
if (suppressed.length == 0) {
// here we have to differentiate by exception message
if ("Exception on try block".equals(e.getMessage())) {
throw e;
} else {
System.out.println(e.getMessage());
}
} else {
// here we will log message from suppressed exception and then throw
System.out.println(suppressed[0].getMessage());
throw e;
}
}
System.out.println("Finished successfully");
}
}
class MyClosable implements AutoCloseable {
@Override
public void close() throws Exception {
throw new RuntimeException("Exception during close");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment