Why and how finally{…} block is NOT meaningless

25 / Jan / 2023 by shivang.chaturvedi 0 comments

A definition first (from the internet):

try-catch-finally is used to handle runtime errors and prevent them from halting the execution of a program.

The finally block triggers regardless of:

  1. what is implemented inside the try-catch block
  2. any errors encountered inside try-catch block
  3. any return statement written inside the try-catch block

Example 1

Consider this example where there’s no error:

(()=>{
try {
console.log(`Try block triggered`)
return 
} catch (error) {
console.log(error)
}finally{
console.log('Finally triggered')
}

console.log(`Rest of the code outside try-catch`)

})()
// Output
Try block triggered
Finally triggered

Note that the “Rest of the code outside try-catch” doesn’t get logged on the console

The finally block will override the return statement written inside the try block.

(()=>{
try {

console.log(`Try block triggered`)

throw `Oops... an error occurred` 

} catch (error) {

return console.log(error)

} finally{

console.log('Finally triggered')
}

console.log(`Rest of the code outside try-catch`)
})()
//Output
Try block triggered
Oops... an error occurred
Finally triggered

Note that the “Rest of the code outside try-catch” doesn’t get logged on the console because of the return statement

From both the example, it becomes apparent that finally block gets executed while the code written outside the try-catch-finally block doesn’t get executed.

Example 3

Consider this example where there is no return statement:

(()=>{
    try {
      
      console.log(`Try block triggered`)
      
      throw `Oops... an error occurred`
    
    } catch (error) {
    
      console.log(error)
   
     }finally{
    
      console.log('Finally triggered')
   
     }
    
  console.log(`Rest of the code outside try-catch`)
})()
//Output
Try block triggered
Oops... an error occurred
Finally triggered
Rest of the code outside try-catch

Note that this time, “Rest of the code outside try-catch” gets printed on the console because there is no return statement in this example implementation

A good use-case for finally block can be to put important codes such as clean up code e.g. closing the file or closing the connection.

Hence, we may not necessarily need a finally{…} block in our code all the time, but it can serve an important purpose for certain similar use-cases.

***

Note of thanks ❤️

Thank you for stopping by. Hope, you find this article useful. Please follow me on medium and help me reach 1k followers 🙏🏻. That will truly encourage me to put out more content.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *