1. Basic usage and logic

1.1 the use of

try{
    //code....
}catch(err){
    //error handling
}finally{
    //no matter what happens in the try/catch (error or no error), this code in the finally statement should run. 
}
Copy the code

1.2 the logical


2. The characteristics of

2.1 the try… Catch only applies to runtime errors and explains that phase errors do not work properly

try{{{{{{{{}catch(err){
    console.error(err)
}
// The engine failed at 'parse-time', so the code could not be understood and therefore could not be captured
Copy the code

2.2 the try… Catch only works synchronously

try{
    setTimeout(function(){
        undefinedVariable;
    },1000)}catch(err){
    console.error(err)
}
// The setTimeout callback is executed when the engine has left the try... Catch the structure
Copy the code

2.3 Finally Invalidates a return statement ina try block

function test(){
  try {
    return 1;
  } catch(error) {
    return 2;
  } finally {
    return 3; }}console.log(test());
/ / 3
Copy the code

Third, the wrong object

When an error occurs in the program, an object containing the details of the error will be generated inside JS, and this object will be passed as a parameter to the catch

For all built-in errors, the error object has two main properties

  1. Name Error type
  2. Message Error message of the text type
  3. Stack (non-standard property) Call stack information when an error occurs, mainly used for debugging
try {
  lalala; // error, variable is not defined!
} catch (err) {
  alert(err.name); // ReferenceError
  alert(err.message); // lalala is not defined
  alert(err.stack); // ReferenceError: lalala is not defined at (... call stack)

  // Can also show an error as a whole
  // The error is converted to string as "name: message"
  alert(err); // ReferenceError: lalala is not defined
}
Copy the code

In theory, we can throw anything as an error object, but the best practice is to throw an object with name, message, to be compatible with the built-in error object

Exterior: Built-in error object

object meaning
ReferenceError Triggered when an undefined variable is referenced
SyntaxError Triggered when an invalid syntax structure is used
TypeError Triggered when a value type is not expected
URIError Incorrect use of global URI functions such asencodeURI(),decodeURI()Such as when the trigger
RangeError rightArrayConstructor uses wrong length value, yesNumber.toExponential(),Number.toFixed()orNumber.toPrecision()Use invalid numbers, etc
EvalError Global functioneval()Error occurred in

4. Better catch and throw strategies

The purpose of catch error is not only to prevent the program from hanging, but also to facilitate debugging and find bugs. Therefore, the error handling strategy can reflect the elegance of the coder

As the saying goes, try to follow the same rule and catch only the mistakes you know

Take a pear 🌰

let json = '{ "age": 30 }'; 
try{
  let user = JSON.parse(json);  
  alert( user.name );
} catch (err) {
  console.error('JSON Error:'+err);
}
Copy the code

Parse (jSON.parse) and user. Name (user.name) do not exist, but both types of errors are printed in the same way. It is not good for debugging

let json = '{"age":30}'
try{
  let user =  JSON.parse(json);
  alert(user.name)
}catch(err){
   if(err instanceof SyntaxError) {console.error('JSON Error:'+err);
   }
   else throw err;
}
Copy the code

Each catch block deals with errors that it knows are likely to occur, that is, when a programmer programs, he or she catches the errors that are expected and throws out errors that he or she might not have expected.


Error handling of Promise

Promises are known to swallow errors, because the implementation of a Promise traps all of them internally, and instead of throwing them out, it finds the nearest onreject callback along the chain, So there are only two ways to handle promise errors

  1. Set the onReject callback
  2. Global capture

For example, 🌰

try{
    new Promise((resolve,reject) = >{
        throw new Error('promise error')
    }).catch(() = >{
        // The error was caught in the latest onreject callback
        console.error(err); })}catch(err){
    // Never execute, promise swallows error
    console.error(err);
}
Copy the code

It is also important to note that either the Executor or the Promise handler swallows internal errors, which are implicitly caught, and the error automatically finds the nearest OnReject callback to pass in

try{
    new Promise((resolve,reject) = >{
        resolve();
    }).then(() = >{
        throw new Error('promise then error');
    }).catch((err){
        console.error(err); })}catch(err){
    Will not be executed until the earth is destroyed
    console.error(err)
}
Copy the code

Similarly, the ondepressing callback registered by THEN will become invalid until onreject callback is found and processed, and the ondepressing callback after onreject callback will be normal

try {
    new Promise((resolve, reject) = > {
        throw new Error('promise error')
    }).then((ret) = > {
        // Error not handled, invalid
        console.log('then1:' + ret)
    }).catch((err) = > {
        // The following sequence is normal
        console.error(err);
        return 'handled'
    }).then((ret) = > {
        // Normal execution
        console.log('then2'+ ret); })}catch (err) {
    // In the same way, the human race will not be executed until it is destroyed
    console.error(err)
}

// Error:promise error
//then2handled
Copy the code

What happens if the entire chain has no catch set?

This error will then go all the way through the earth’s core and trigger different global events depending on the host environment. For example, the unhandledrejection event will be triggered in the browser, and the Unhandledrejection event will be triggered in the node environment. Display the information to the programmer or user

One day 1:chromium / v8 / v8 / 3.29.45Promise internal error capture


One day 2:Async /await error catching


Six, performance loss

Shipped with Node 8.3 and latest Chrome After V8 Version 6 (Shipped with Node 8.3 and latest Chrome), The performance of code inside try-catch is the same as that of normal code. —— burst stack net

(Slightly tested, almost the same)

Please click on me for detailed discussion

reference

  1. Error handling, “try… catch”
  2. Try/Catch in JavaScript – How to Handle Errors in JS
  3. JavaScript try… catch Statement
  4. Use promises for error handling