Exceptions in Programming – Is the ‘Finally’ Block Necessary in Try-Catch-Finally?

exception handling

Some languages (such as C++ and early versions of PHP) don't support the finally part of a try ... catch ... finally construct. Is finally ever necessary? Because the code in it always runs, why wouldn't/shouldn't I just place that code after a try ... catch block without a finally clause? Why use one? (I'm looking for a reason/motivation for using/not using finally, not a reason to do away with 'catch' or why it's legal to do so.)

Best Answer

In addition to what others have said, it's also possible for an exception to be thrown inside the catch clause. Consider this:

try { 
    throw new SomeException();
} catch {
    DoSomethingWhichUnexpectedlyThrows();
}
Cleanup();

In this example, the Cleanup() function never runs, because an exception gets thrown in the catch clause and the next highest up catch in the call stack will catch that. Using a finally block removes this risk, and makes the code cleaner to boot.