Why are both code blocks executed in the following code try catch?

when the following js is executed, alert prints 2, and then alert 1. That is to say, finally, is executed first and then return. Is there any application scenario for this execution sequence?


function Test() {
    var a = {b: 1}
    try {
        return a.b;
    } finally {
        a={b:2}
        alert(""+a.b)
    }
}
alert(Test())
</script>
</body>
</html>
Mar.03,2021

usage scenarios: https://blog.csdn.net/aitangy.
means that you cannot handle the current exception, or if you don't need to handle it, you won't throw catch, directly. However, if some cleanup work needs to be done, it is executed in finally, because the return statement in try {} must be executed after finally is executed (if return is written in finally, the method will be exited directly, and the return statement in try will not be executed again).


there are no catch statements in your code, but finally statements. You can check the definition of finally statements and be sure to execute


.
Why execute finally first and then return in try?

this itself is the execution of the try.catch.finally structure.

you can understand that finally is in the current function and belongs to the scope of the current function. If it is really returned in the try, the execution process has jumped out of the scope of the current function, and the code in the current function can no longer be executed. So finally needs to be executed before the return in try actually returns, and then returns.


the complete structure is

try{
... //
}catch{
... //
}finally{
... //try
}

I thought I was blind. I looked at it five times and couldn't find out where catch was

.
Menu