Avoid Method Chaining When Using Multiple AutoCloseable Instances

The try-with-resources statement introduced in Java 7 allows us to adopt an approach where certain objects could be opened, being visible in the try block, and immediately closed when the execution reaches the end of that scope. This was a huge improvement for managing scarce resources, in comparison with the old approach of overriding the finalize() method (which we never exactly know when  will be executed.)

Over the years, I was repeatedly seeing the following approach on some applications, which motivated me to write this post. Consider this code snippet for executing an SQL statement using JDBC: