Initializing one-time resources outside or inside try / finally

I saw two ways to acquire and manage resources. Or:

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 excludes the condition if, and the second (I suppose) handles the case of a thread interruption immediately after the assignment, but before entering the block try. What other pros and cons do these styles make on top of each other? Which one should I use?

+3
source share
3 answers

In C #, just use the using statement:

using (Resource resource = GetResource())
{
    /* Do something */
}

, , IDisposable. ( Java try-with-resources , AutoCloseable.)

Java try - . : , . .

+6

+4

getResource() , resource null, getResource() , , getResource() , null resource.close(). , - try; , getResource() .

-1

All Articles