问题
I have seen two ways of acquiring and disposing resources. Either:
Resource resource = getResource();
try { /* do something with resource */ }
finally { resource.close(); }
or:
Resource resource = null;
try { resource = getResource(); /* do something with resource */ }
finally { if (resource != null) resource.close(); }
I was wondering which style is preferable. The first one avoids the if condition, while the second one (I presume) handles the case of thread abort right after the assignment but before entering the try block. What other pros and cons do these styles have over each other? Which one should I preferably use?
回答1:
In C#, just use the using statement:
using (Resource resource = GetResource())
{
/* Do something */
}
This is the idiomatic way of cleaning up resources, and relies on the resource in question implementing the IDisposable interface. (Java now has a similar try-with-resources statement, for resources implementing AutoCloseable.)
There's no risk of a thread abort in Java happening between the assignment and entering the try block - aborts only occur during sleeps and waits. EDIT: I can't actually find this in the spec, which is somewhat worrying. Hmm.
回答2:
first one is preferable
回答3:
If getResource() throws an exception then resource will be null, getResource() does not return anything in the case of an exception. So, as long as getResource() can throw an exception, always check for null before calling resource.close(). I feel the best way to organize this code is to put everything inside the try block; make it clear clear that getResource() throws exceptions.
来源:https://stackoverflow.com/questions/463029/initializing-disposable-resources-outside-or-inside-try-finally