Could you not finally?

twitter logo github logo ・1 min read

Do you know of any way to skip the execution of a finally block?

function fn(){
    try{
        return 1;
    }finally{
        console.log(2);
    }
}
fn();
// Logs 2
// Returns 1

A bit more bizarre example would be if you use return in finally:

function fn(){
    try{
        return 1;
    }finally{
        return 2;
    }
}
fn(); // 2

It seems like finally cannot be stopped!

twitter logo DISCUSS (2)
markdown guide
 

The point of finally is to run after a try...catch block no matter what happens. From the MDN

Note that the finally clause executes regardless of whether or not an exception is thrown. Also, if an exception is thrown, the statements in the finally clause execute even if no catch clause handles the exception. You can use the finally clause to make your script fail gracefully when an exception occurs; for example, to do general cleanup, you may need to release a resource that your script has tied up.

 

Short of killing the process, calling another function within try{..}, or doing a while(true) within try{...}, the finally block will execute, period.

Classic DEV Post from Jan 12

Kotlin: How Can a Programming Language be so Young And so Mature at The Same Time?

In this article, we’re going to explore why young programming languages with modern features can’t be adopted quickly. Additionally, we’re going to take a look at one exceptional example that got specific parameters right to be both young, modern and mature, just ready for adoption at small and big scale.

Dimitar Nestorov profile image
I cook JavaScript. I generally prefer the taste of TypeScript and spice up with React. webpack is my mixer. All of this I put in a bowl of Yarn Workspaces.
  1. Follow languages πŸ€“
  2. Follow great devs πŸ‘‹
  3. Stay in the loop
  4. Join Now