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 .
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, ie 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.
Finally its always executed the last. So it overrides any other return you have. Therefore, your method returns false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.