Note. I’m not sure if it’s on-topic since it concerns a specific programming language, not software engineering in general. However, I decided to give it a try
Suppose I create a closeable resource with a try-with-resources block. In case something happens, I want to log an informative message in the catch block. The problem is I need a reference to the resource which is scoped to the try block. Try-with-resources can’t accept a non-final reference
try (MyResource resource = getMyResource()) {
// do something with the resource
} catch (MyResourceException e) {
logger.error("This happened to {}: {}", /* can't do, out of scope */ resource.getName(), e.getMessage());
}
Is it a good reason to ditch try-with-resources altogether? I don’t think so
What do you recommend?
In the actual project, MyResource
is a wrapper over a PreparedStatement
. It helps to log an SQL query that caused an error