What are the errors that try..catch cannot catch? What are the precautions?

Time:2022-11-24

Author: Ashish Lahoti
Translator: Frontend Xiaozhi
Source: codingnconcept

Search [Great Move to the World] on WeChat, and I will share with you the front-end industry trends, learning paths, etc. as soon as possible.
This articleGitHubhttps://github.com/qq449245884/xiaozhiIt has been included, and there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

In today’s content, let’s learn how to usetrycatchfinallyandthrowDo error handling. We’ll also talk about the built-in error object in JS (Error, SyntaxError, ReferenceErroretc.) and how to define custom errors.

1. Use try..catch..finally..throw

To handle errors in JS, we mainly usetrycatchfinallyandthrowkeywords.

  • tryblock contains the code we need to inspect
  • keywordsthrowUsed to throw custom errors
  • catchblock handles caught errors
  • finallyA block is a block that will be executed regardless of the final result, and you can do some things that need to be dealt with in this block

1.1 try

eachtryblock must be associated with at least onecatchorfinallyblock, otherwise throwsSyntaxErrormistake.

we use alonetryblock to verify:

try {
  throw new Error('Error while executing the code');
}
ⓧ Uncaught SyntaxError: Missing catch or finally after try

1.2 try..catch

It is recommended totryandcatchblock, it gracefully handlestryThe error thrown by the block.

try {
  throw new Error('Error while executing the code');
} catch (err) {
  console.error(err.message);
}
➤ ⓧ Error while executing the code

1.2.1 try..catchwith invalid code

try..catchCannot catch invalid JS code, such astryblock is syntactically incorrect, but it will not becatchblock capture.

try {
  ~!$%^&*
} catch(err) {
  console.log("This will not be executed");
}
➤ ⓧ Uncaught SyntaxError: Invalid or unexpected token

1.2.2 try..catchwith asynchronous code

same,try..catchExceptions thrown in asynchronous code cannot be caught, such assetTimeout

try {
  setTimeout(function() {
    noSuchVariable;   // undefined variable
  }, 1000);
} catch (err) {
  console.log("This will not be executed");
}

uncaughtReferenceErrorwill fire after 1 second:

➤ ⓧ Uncaught ReferenceError: noSuchVariable is not defined

So, we should use inside asynchronous codetry..catchto handle errors:

setTimeout(function() {
  try {
    noSuchVariable;
  } catch(err) {
    console.log("error is caught here!");
  }
}, 1000);

1.2.3 Nestingtry..catch

We can also use nestedtryandcatchThe block throws an error upwards, as follows:

try {
  try {
    throw new Error('Error while executing the inner code');
  } catch (err) {
    throw err;
  }
} catch (err) {
  console.log("Error caught by outer block:");
  console.error(err.message);
}
Error caught by outer block:
➤ ⓧ Error while executing the code

1.3 try..finally

It is not recommended to use onlytry..finallyinstead ofcatchblock and see what happens below:

try {
  throw new Error('Error while executing the code');
} finally {
  console.log('finally');
}
finally
➤ ⓧ Uncaught Error: Error while executing the code

Note two things here:

  • Even fromtryAfter the block throws an error, it also executesfinallypiece
  • if there is notcatchblock, errors will not be handled gracefully, resulting in uncaught errors

1.4 try..catch..finally

It is recommended to usetry...catchblock and optionalfinallypiece.

try {
  console.log("Start of try block");
  throw new Error('Error while executing the code');
  console.log("End of try block -- never reached");
} catch (err) {
  console.error(err.message);
} finally {
  console.log('Finally block always run');
}
console.log("Code execution outside try-catch-finally block continue..");
Start of try block
➤ ⓧ Error while executing the code
Finally block always run
Code execution outside try-catch-finally block continue..

Two more things to note here:

  • existtryAfter an error is thrown in the block, the following code will not be executed
  • Even thoughtryAfter the block throws an error,finallyblock still executes

finallyBlocks are typically used to clean up resources or close streams, like so:

try {
  openFile(file);
  readFile(file);
} catch (err) {
  console.error(err.message);
} finally {
  closeFile(file);
}

1.5 throw

throwstatement is used to raise an exception.

throw <expression>
// throw primitives and functions
throw "Error404";
throw 42;
throw true;
throw {toString: function() { return "I'm an object!"; } };

// throw error object
throw new Error('Error while executing the code');
throw new SyntaxError('Something is wrong with the syntax');
throw new ReferenceError('Oops..Wrong reference');

// throw custom error object
function ValidationError(message) {
  this.message = message;
  this.name = 'ValidationError';
}
throw new ValidationError('Value too high');

2. Error handling in asynchronous code

Error handling for asynchronous code can bePromiseandasync await

2.1 Promises inthen..catch

we can usethen()andcatch()Chain multiple Promises to handle errors for a single Promise in the chain, like so:

Promise.resolve(1)
  .then(res => {
      console.log(res); // print '1'

      throw new Error('something went wrong');  // throw error

      return Promise.resolve(2); // this will not be executed
  })
  .then(res => {
      // won't execute here either, because the error hasn't been handled yet
      console.log(res);    
  })
  .catch(err => {
      console.error(err.message);  // Print 'something went wrong'
      return Promise.resolve(3);
  })
  .then(res => {
      console.log(res); // print '3'
  })
  .catch(err => {
      // here will not be executed
      console.error(err);
  })

Let’s look at a more realistic example where we usefetchcalls the API, which returns apromiseobject, we usecatchBlocks gracefully handle API failures.

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}

fetch("http://httpstat.us/500")
    .then(handleErrors)
    .then(response => console.log("ok"))
    .catch(error => console.log("Caught", error));
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)

2.2 try..catchandasync await

existasync awaitused in try..catchEasier:

(async function() {
    try {
        await fetch("http://httpstat.us/500");
    } catch (err) {
        console.error(err.message);
    }
})();

Let’s look at the same example, where we usefetchCall the API, which returns apromiseobject, we usetry..catchBlocks gracefully handle API failures.

function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
}

(async function() {
    try {
      let response = await fetch("http://httpstat.us/500");
      handleErrors(response);
      let data = await response.json();
      return data;
    } catch (error) {
        console.log("Caught", error)
    }
})();
Caught Error: Internal Server Error
    at handleErrors (<anonymous>:3:15)
    at <anonymous>:11:7

3. Built-in errors in JS

3.1 Error

JavaScript has a built-in error object, which is usually represented bytryblock throws, and atcatchblock capture,ErrorThe object contains the following properties:

  • name: is the name of the error, such as “Error”, “SyntaxError”, “ReferenceError”, etc.
  • message: A message about the details of the error.
  • stack: is the error’s stack trace for debugging purposes.

we create aErrorobject, and view its name and message properties:

const err = new Error('Error while executing the code');

console.log("name:", err.name);
console.log("message:", err.message);
console.log("stack:", err.stack);
name: Error
message: Error while executing the code
stack: Error: Error while executing the code
    at <anonymous>:1:13

JavaScript has the following built-in errors, derived fromErrorobject inherited from

3.2 EvalError

EvalErrorrepresent the globaleval()function error, this exception is no longer thrown by JS, it exists for backward compatibility.

3.3 RangeError

When the value is out of range, it will throwRangeError

➤ [].length = -1
ⓧ Uncaught RangeError: Invalid array length

3.4 ReferenceError

When referencing a variable that does not exist, will throwReferenceError

➤ x = x + 1;
ⓧ Uncaught ReferenceError: x is not defined

3.5 SyntaxError

When you use any wrong syntax in your JS code, it will throwSyntaxError

➤ function() { return 'Hi!' }
ⓧ Uncaught SyntaxError: Function statements require a function name

➤ 1 = 1
ⓧ Uncaught SyntaxError: Invalid left-hand side in assignment

➤ JSON.parse("{ x }");
ⓧ Uncaught SyntaxError: Unexpected token x in JSON at position 2

3.6 TypeError

Throws if the value is not of the expected typeTypeError

➤ 1();
ⓧ Uncaught TypeError: 1 is not a function

➤ null.name;
ⓧ Uncaught TypeError: Cannot read property 'name' of null

3.7 URIError

If the global URI method is used in the wrong way, it will throwURIError

➤ decodeURI("%%%");
ⓧ Uncaught URIError: URI malformed

4. Define and throw custom errors

We can also define custom errors in this way.

class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = "CustomError";
  } 
};

const err = new CustomError('Custom error while executing the code');

console.log("name:", err.name);
console.log("message:", err.message);
name: CustomError
message: Custom error while executing the code

We can further enhanceCustomErrorobject to contain the error code

class CustomError extends Error {
  constructor(message, code) {
    super(message);
    this.name = "CustomError";
    this.code = code;
  } 
};

const err = new CustomError('Custom error while executing the code', "ERROR_CODE");

console.log("name:", err.name);
console.log("message:", err.message);
console.log("code:", err.code);
name: CustomError
message: Custom error while executing the code
code: ERROR_CODE

existtry..catchblock use it:

try{
  try {
    null.name;
  }catch(err){
    throw new CustomError(err.message, err.name);  //message, code
  }
}catch(err){
  console.log(err.name, err.code, err.message);
}

CustomError TypeError Cannot read property ‘name’ of null

I’m Xiaozhi, see you next time!


The bugs that may exist after the code is deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time is spent on log debugging. By the way, I recommend a useful bug monitoring tool for everyone.Fundebug

original:https://codings.com/javascrip…

comminicate

Have dreams, have dry goods, WeChat search【Great move to the world】Pay attention to this dishwashing wisdom who is still washing dishes in the early morning.

This articleGitHubhttps://github.com/qq449245884/xiaozhiIt has been included, and there are complete test sites, materials and my series of articles for interviews with first-line manufacturers.

What are the errors that try..catch cannot catch? What are the precautions?