How to handle the try/catch/finally blocks in JavaScript

The finally block will execute after the try block and catch block execute. The finally block will be executed regardless of whether or not the error is thrown.

When using the try/catch/finally blocks, we should aware of which block’s return values will be returned. For example, consider the following function:

function get() {
try {
console.log("Inside try");
throw new Error("Return error");
return 10;
} catch(e){
console.log("Inside catch");
return 20
} finally{
console.log("Inside finally");
return 30;
}
console.log("Outside try...catch...finally");
return 40;
}
console.log("The value is ", get());

You can see that in the above code we have a return statement inside each try/catch/finally block, and another one outside the try/catch/finally blocks.

In our case:

  • The return 10 in the try block will not be reached because we throw a Return error before reaching the return statement.

  • Now, the catch block will catch the Return Error, and the return 20 will not be considered because there is a finally block present.

  • Upon executing the finally block, the return 30 will be returned. Since this is returned, the outside return 40 will not be executed.

Free Resources