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 10in thetryblock will not be reached because we throw aReturn errorbefore reaching thereturnstatement. -
Now, the catch block will catch the
Return Error, and thereturn 20will not be considered because there is afinallyblock present. -
Upon executing the
finallyblock, thereturn 30will be returned. Since this is returned, the outsidereturn 40will not be executed.