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

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b351a2-2bf5e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b351a2-2bf5e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?