Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uses of the finally statement

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.

like image 516
Gabriel Llamas Avatar asked Aug 15 '13 10:08

Gabriel Llamas


People also ask

What are the uses of finally statement in exception handling?

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.

What is a finally statement?

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.

What finally class why it is used?

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.

What are the benefits of using finally keyword?

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.


1 Answers

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();
like image 138
Morteza Faghih Shojaie Avatar answered Sep 20 '22 20:09

Morteza Faghih Shojaie