I have tried this code in javascript
function abc(){ try{ console.log(0); throw "is empty";} catch(err){ console.log(1); return true; } finally{return false;} return(4); } console.log(abc());
I got output as false. I understand Finally always execute regardless of result of try catch but what happen to return statement in catch .
Yes, we can write a return statement of the method in catch and finally block.
Upon the completion of finally block execution, control goes back to the return statement in the try block and returns “returning from try block”. If finally block has a return statement, then the return statements from try/catch blocks will be overridden.
In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.
4.4. 1 Write return statement inside try-block & at the end of method; that is just before end of method.
I understand Finally always execute regardless of result of try catch but what happen to return statement in catch .
Return statement in catch
will be executed only if the catch
block is reached, i.e. if there is an error thrown.
For example
function example() { try { throw new Error() return 1; } catch(e) { return 2; } finally { } }
example()
will return 2
since an error was thrown before return 1
.
But if there is a finally
block and this finally
block has a return
statement then this return
will override catch
return statement.
For example
function example() { try { throw new Error() return 1; } catch(e) { return 2; } finally { return 3; } }
Now example()
will return 3
.
In your example, there is a return statement after the finally block. That statement will never get executed.
Try
function example() { try { throw new Error() return 1; } catch(e) { return 2; } finally { return 3; } console.log(5) return 4; }
It only outputs 3
. 5
is never printed since after finally
block value is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With