Doubts about the exception capture process of node Asynchronous callback

try{
    var b = 7 ;
    setTimeout(function(){console.log(b);throw new Error("")},2000)
}catch(e){
    console.log(1)
    console.log(e.message)
}

console print result

7;
Uncaught Error: 
    at <anonymous>:3:48

printing out 7 means that after the try has finished executing the code, it still retains its context without popping the stack. After the timer is executed in the timer module, the bound callback function is put into the task queue, then taken out by the js execution stack, and put into the scope of the try (because of the scope of the js function, internal variables cannot be accessed externally. At this point, the value of b means that the execution scope of the callback function is within try), so why does catch not catch the exception thrown in the try at this time?

Dec.01,2021

just write finally . try/catch has been executed long ago. It is not an exception thrown internally, it is an exception thrown by the timer callback.


try{
    var b = 7 ;
}catch(e){
    console.log(1)
    console.log(e.message)
}
console.log(b);

in fact, only catch clauses create a block scope, try you can understand it as an explicitly declared error detection mechanism. So the latter statement is actually out of the scope of try detection and is waiting in the asynchronous callback, so it naturally cannot be triggered to catch

.
Menu