CoffeeCups :
What happens when a try-with-resource throws an exception which is caught outside? Will a cleanup still be performed?
Sample:
public void myClass() throws customException {
try (Connection conn = myUtil.obtainConnection()) {
doSomeStuff(conn);
if (someCheck)
throw new customException(somePara);
doSomeMoreStuff(conn);
conn.commit();
} catch (SQLException e) {
log.error(e);
}
}
The part I'm concerned with is when the customException is thrown. I do not catch this exception with the catch of my try-with-resource. Hence I wonder if the connection cleanup will be performed in this scenario.
Or do I need to catch and rethrow the connection, like this:
public void myClass() throws customException {
try (Connection conn = myUtil.obtainConnection()) {
doSomeStuff(conn);
if (someCheck)
throw new customException(somePara);
doSomeMoreStuff(conn);
conn.commit();
} catch (SQLException e) {
log.error(e);
} catch (customException e) {
throw new customException(e);
}
}
Olivier Grégoire :
Example of execution with an exception thrown in the
Yes, the cleanup will happen... if the close()
method correctly handles the cleanup:
Example of execution
public class Main {
public static void main(String[] args) throws Exception {
try (AutoCloseable c = () -> System.out.println("close() called")) {
throw new Exception("Usual failure");
}
}
}
(shortened by Holger in the comments)
Output on stdout:
close() called
Output on stderr:
Exception in thread "main" java.lang.Exception: Usual failure
at Main.main(Main.java:4)
Example of execution with an exception thrown in the close()
method
(suggested by Holger in the comments)
public class Main {
public static void main(String[] args) throws Exception {
try (AutoCloseable c = () -> { throw new Exception("Failure in the close method"); }) {
throw new Exception("Usual failure");
}
}
}
No output on stdout.
Output on stderr:
Exception in thread "main" java.lang.Exception: Usual failure
at Main.main(Main.java:4)
Suppressed: java.lang.Exception: Failure in the close method
at Main.lambda$main$0(Main.java:3)
at Main.main(Main.java:3)