What is the need of finally block when we can close files and all in catch block

What is the need of finally block when we can close files and all in catch block. Whatever thing we are closing or clearing in finally block can it be done in catch block. Please tell me if I am wrong.

Jon Skeet
people
quotationmark

You normally want to perform the same clean-up action whether an exception is thrown or not. Doing that just with catch blocks is painful - especially if you want to make sure that you only call close() once, even if that throws. You'd end up with:

bool closeCalled = false;
OutputStream stream = ...;
try {
   stream.write(...);
   closeCalled = true;
   stream.close();
} catch (IOException e) {
   if (!closeCalled) {
       // TODO: Add another try/catch here? What do we want to
       // do if this throws?
       stream.close();
   }
   throw e;
}

Compare that with:

OutputStream = ...;
try {
   stream.write(...);
} finally {
   // TODO: Still need to work out what to do if this throws.
   stream.close();
}

Or best:

try (OutputStream stream = ...) {
    stream.write(...);
}

Personally, I think the last example is by far the cleanest - do you really want the first block of code everywhere? Oh, and this is a simple case - we're only catching a single exception. Imagine repeating that code in each catch clause, and if there are multiple ways of exiting the try block, repeating the close call for each of those, too... ick.

Additionally, as pointed out by Nicolas in comments, there are all those unchecked exceptions which you don't catch (and which can be painful to catch and rethrow). Fundamentally, the principle of "I just want to clean up my resources whatever happens" is very, very compelling...

people

See more on this question at Stackoverflow