The reason for writing this blog is that when I used try and catch to catch Promise errors in my work recently, sometimes I could not catch them, and sometimes I was caught by Promise. Catch. I am not very clear about the capture mechanism and order After the inspection
preface
Usually, try catch is used too much when trying code, especially for people with low “security”, basically try catch everywhere, afraid of JS error, and then the whole page will die.
Why is it so insecure? Because the boundaries are blurred, a lot of newbies don’t know what kind of exception a try and catch catches, and whether or not they can catch a Promise, and if a Promise catches a.catch, who catches it
So we need to figure out try catch and be a code farmer with high sense of security!!
-
Interviewer: Please describe in one sentence whether JS exceptions can be caught by try catch.
-
Interviewer: Asynchronous methods don’t capture…
-
Interviewer: Do not memorize the answer, please describe in one sentence whether JS exception can be tried catch!
-
Interviewer: Silence ing …………
-
Interviewer: The exception that can be caught must be thrown when the thread has entered a try catch but the try catch has not finished.
-
Interviewer: Silence ing …………
-
Interviewer: When can I start?
-
Laugh and talk, get the offer …………
About how trycatch works
When a program runs inside a try catch, if no error is reported, the code in the catch is ignored. If an error is reported, the code following the try is not executed and the code in the catch is executed instead.
When does a try catch catch catch an exception?
The exception that can be caught must be thrown when the thread has entered a try catch but the try catch has not finished
1. Syntax errors cannot be caught
Because the syntax error is reported during the syntax check phase, the thread execution cannot catch the exception before it enters the try catch block. Such as:
try{
a.
}catch(e){
console.log("error",e);
}
// output
Uncaught SyntaxError: Unexpected token '}'
Copy the code
2, the syntax is correct, when the thread enters a try catch, can catch
function d(){a.b; } try{ d(); }catch(e){ console.log("error",e); } // output error ReferenceError: a is not definedCopy the code
The code execution goes into a try catch, and when d() is executed, the thread execution is inside the try, so it catches it.
3. Asynchrony cannot be captured
try{
setTimeout(()=>{
console.log(a.b);
}, 100)
}catch(e){
console.log('error',e);
}
console.log(111);
//output
111
Uncaught ReferenceError: a is not defined
Copy the code
Because setTimeout is an asynchronous function, and try catch is actually code executed synchronously and sequentially. By the time the events inside setTimeout enter the event queue, the main thread has already left the try catch, so the try catch cannot catch the errors of the asynchronous function.
4. The Promise exception cannot be caught
Try {new Promise(() => {throw new Error('new Promise throw Error '); }); } catch (error) { console.log(error); }Copy the code
If an asynchronous method in a try fails to catch an exception, the catch cannot be caught because: When an asynchronous function throws an exception, for the macro task, the function has already been pushed on the stack and is not on the try-catch stack, so the try-catch does not catch the error. For microtasks, such as promises, exceptions in the promise constructor can only be caught by the native reject (.catch) function.
If you want to catch the Promise exception
- 1.Promise exceptions are not absolutely uncatchable, as follows
async function fn() {
try {
await new Promise(() => {
throw new Error('new promise throw error');
});
} catch (error) {
console.log(error);
}
}
fn()
Copy the code
Code run result
This time, the Promise exception can be caught because async and await are not added. Normally, when async and await are not added, after the Promise is executed, while waiting for the Promise callback,try and catch have been executed, so it cannot be caught. However, after async and await are added, TR will be caught Y and catch must wait for the promise callback to finish before they can continue. If trycatch is not finished, the promise will throw an exception, which will naturally be caught by the catch
- 2. Whether the promise exception is caught by catch or.catch
Now let’s change the code
async function fn() {
try {
await new Promise(() => {
throw new Error('new promise throw error');
}).catch(error=>{
console.log('.catch',error);
})
} catch (error) {
console.log('try,catch',error);
}
}
fn()
Copy the code
.catch, as you all know, is used to catch promise exceptions. When we have a.catch, the error is caught by the.catch before it enters the catch, so it doesn’t go any further. Yes try,catch)
At this point, we can see that the error was caught by.catch, so what if instead of throwing an error, we just returned a reject
Async function fn() {try {const res = await new Promise((resove,reject) =>{return reject(' catch ')}). Catch (error=>{ The console. The log (' be promise. Catch, error); })} catch (error) {console.log(' try,catch',error); } } fn()Copy the code
The results
The Promise exception, if it says.catch, it gets caught first, if it doesn’t, it gets caught by try catch,
conclusion
From the above analysis, we can see that the exception that can be caught by a try catch can only be caught when the thread execution is already inside the try catch block at the time of the error. Also,try and catch can catch a Promise if we use async and await, but we don’t recommend it. After all,Promise exceptions have their own.catch to catch, and it’s easier to use, right?
So, insecure brothers, after reading this article, stop writing trycatch everywhere, our own code is not as fragile as we thought
If there is something wrong or needs to be improved in the above article, you can comment or send a private letter below, and learn and communicate together
Edit is not easy, a see official, dot praise bai!!!!!!
reference
- Blog.csdn.net/weixin_3985…
- Blog.csdn.net/xiaoluodeca…