Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use finally?

Every documentation I can find for the finally part of a try-catch-finally construct is the same: Code within the finally block runs whether or not an exception occurred, and it is useful for putting cleanup code.

My question is... why?

I mean, how is this:

try {
    doSomething();
}
catch( e) {
    somethingFailed(e);
}
finally {
    cleanupSomething();
}

any better than this:

try {
    doSomething();
}
catch( e) {
    somethingFailed(e);
}
cleanupSomething();

Put another way, how is finally any different to just continuing on?

like image 319
Niet the Dark Absol Avatar asked May 25 '26 01:05

Niet the Dark Absol


1 Answers

Finally is actually very useful. It is definitely a worthy tool to have around, as it essentially works to protect resources that must be managed without waiting for the garbage collector. There are other uses, but this is its primary one.

Why should we use it though? Why not just place the disposal after the catch statement (assuming all exceptions were caught)?

There is a very good reason for this, and that is for when control leaves the try statement. If this occurs, for any reason, finally will get hit before control leaves. So, for example, if a return, continue, break, goto, or an exception if not caught -- if any of that happens in the try block finally will execute whereas the code in your post will not because control had already left. If that had been an important resource it was just leaked.

like image 138
Travis J Avatar answered May 27 '26 14:05

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!