The Oracle Java documentation for the then-new try-with-resources shows all examples with the AutoCloseable in question being constructed in the try(...):
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
...
}
That seems secure in the sense that even if the constructor (as opposed to some subsequent event) already acquires resources that have to be released, they would be released if we ran into an exception.
However, as, e.g., https://www.baeldung.com/java-try-with-resources points out, starting with Java 9, we can use effectively final resources initialized before the try(...):
FileOutputStream fos = new FileOutputStream("output.txt");
try (fos) {
// do stuff
}
In a similar, pre-Java-9 vein, I have seen:
CustomStreamLikeThing connection = new CustomStreamLikeThing("db_like_thing");
// ... do some stuff that may throw a RuntimeException
try (CustomStreamLikeThing connection2=connection) {
// do some more stuff
}
Which seems legal, but at the same time to somewhat weaken the concept: If the CustomStreamLikeThing acquires closeable resources, they may not be released.
Are there guidelines about when the constructor of an AutoCloseable should be enclosed in the try(...), or is this a matter of taste (as in "enclose all those things that I think could throw an exception")?