Is there any reason to put code in a finally block as opposed to just having code after the try...catch statement. Surely in both cases the code gets run anyway
try {
something();
} catch (error) {
error_handling_with(error);
}
// code here gets executed whether in finally clause or not.
finally_something();
Is there any place where finally is essential after try...catch? I can see it has a use in Promises, just not here.
finally basically runs even if you have an early-return from try-catch or even if you don't handle the error in the try-catch. Here is an example I like:
function myFunction() {
try {
console.log('inside "try"');
return
} finally {
console.log('inside "finally"');
}
console.log("after try-finally");
}
myFunction()
When you run myFunction(), it will print the following:
inside "try"
inside "finally"
Since you returned from try, it didn't execute any instructions after the try-finally block. But, Javascript did execute the finally block.
I think you have received the correct technical answer for this. However, if you are asking for practical usage, one situation is when you want to close a connection in any case. Here is a pseudo-code to explain:
openConnection();
try {
DoSomething();
return;
} catch (anomaly) {
handleAnomaly();
} finally {
closeConnection();
}
See in the above case, you close the connection in every case whether there is a handled exception, un-handled exception or happy flow, your connection will be closed and that too without duplication of code.
Catch/Finally are optional, the only rule is that 1 of them must always exist.
Finally exists so that code can always be run, disregarding whether or not an error was caught or not.
I would argue that in some cases they are added when they're not needed, but it helps readability, in other cases it might just be a habit.