Created
January 25, 2018 17:14
-
-
Save saberduck/5bb8d91fb62614692d010458e62c7073 to your computer and use it in GitHub Desktop.
try-with-resources and suppressed exceptions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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