This is a very basic question. In Java I use the finally statement to close resources because "it's a good practice". I've been developing in Javascript and then in Node.js during some years and I've never used the finally
statement. I know that in Node.js all of us follow the first parameter error handling pattern. Anyway, the 2 following snippets do the same:
try{ throw 123 }catch (e){ }finally{ console.log(1) }
.
try{ throw 123 }catch (e){ } console.log(1)
Both print 1.
Why is finally
a keyword if it has no real benefit? The clean up code can be put inside the catch.
The finally statement is generally used to clean up after the code in the try statement. If an exception occurs in the try block and there is an associated catch block to handle the exception, control transfers first to the catch block and then to the finally block.
Defines a final end block for any ABL block. An end block is an ABL block that can occur only within another block. The block containing the end block is known as the associated block . End blocks must occur between the last line of executable code in the associated block and its END statement.
The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you just wish to execute, despite what happens within the protected code.
But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break . Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
Just a simple and straightforward example that shows the difference. There is a return
that breaks the function completion, but the console.log
in finally
is called while the last console.log
is skipped.
let letsTry = () => { try { // there is a SyntaxError eval('alert("Hello world)'); } catch(error) { console.error(error); // break the function completion return; } finally { console.log('finally') } // This line will never get executed console.log('after try catch') } letsTry();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With