The standard idiom for resource handling in Java:
final Resource resource = acquire(); try { use(resource); } finally { resource.dispose(); }
Common errors include trying to use the same try with the exception of catch and subsequent use, which creates a mess using null , etc.
Execute Around Idiom can extract such constructs, although the Java syntax is verbose.
executeWith(new Handler() { public void use(Resource resource) { ... }});
source share