As we all know, JS is in the position of front-end development. It’s really important to learn it well.

The following article introduces error handling.

Error handling

During development, we will encapsulate some tool functions and then give them to others to use:

  • Some parameters may be passed in the process of being used by others.
  • For functions, we need to validate these parameters, or we may get undesirable results.

A lot of times we might validate a parameter that is not what we want, and just return. But a return has a big downside: the caller doesn’t know if the function didn’t execute properly or if the result is undefined.

In fact, the right thing to do would be to let the outside world know that an error was reported inside the function if some validation was not passed.

How can a function tell the outside world that it has an internal error?

  • Throw an exception with the throw keyword.
  • The throw statement is used to throw a user-defined exception.
  • When a throw statement is encountered, the current function execution is stopped (statements following the throw are not executed).
  • If the thrown error is not handled, the entire program stops.

If we execute the code, an error will be reported, and when we get the error message, we can fix the code in time.

throw

A throw expression is an expression that can be followed by a throw to indicate specific exception information.

What types can the throw keyword follow?

  • Basic data types: such as number, String, Boolean.
  • Object types: Object types can contain more information.
    // 2. It is more common to throw an object type
    throw { errorCode: -1001.errorMessage: "Type cannot be 0~" }
Copy the code
  • In fact, in development, t throws Error messages by calling the Error class.
    const err = new Error("Current type is wrong ~")
    throw err
Copy the code

Error contains three attributes:

  • Messsage: Message passed when an Error object is created.
  • Name: The name of the Error, usually the same as the class name.
  • Stack: The entire Error message, including the function call stack. When we print the Error object directly, we print the stack.

Error has some subclasses of its own:

  • RangeError: Error type used when a subscript value is out of bounds.
  • SyntaxError: Error type used to parse syntax errors.
  • TypeError: error type used when a TypeError occurs.
    function foo(type) {
      console.log("Function foo starts executing.")

      if (type === 0) {

        throw  new TypeError("Current type is wrong ~")

        // Note: if an exception has already been thrown in a function, no further code will be executed
        console.log("The code following function foo")}console.log("Function foo completes execution")
    }

    foo(0)

    console.log("Subsequent code continues to execute ~")
Copy the code

Exception handling

As you can see from the above, if a thrown error is not handled, execution of the program will be terminated.

  • This is because if we call a function and the function throws an exception, but we do not handle the exception, the exception is passed on to the previous function call.
  • If the top-level (global) code still does not handle the exception, an error is reported and the program is terminated.

Let’s take a look at how this code passes exceptions:

    function foo() {
      throw new Error("foo----")}function bar() {
      foo()
    }
    
    function test() {
      bar()
    }

    test()

Copy the code
  • Foo throws an exception when it is executed, which means our bar function gets it.
  • But bar does not handle this exception, so the exception is passed to the function that called bar, which is the test function.
  • But the test function remains unprocessed and continues to be passed into our global code logic.
  • If it is still not processed, the program will terminate and no further code will be executed.

So we need to catch errors where they occur in order for the program to run correctly. So you need try catch syntax.

    function foo() {
      throw new Error("foo----")}function bar() {
      try {
      foo(0)
        console.log("Bar function continues to run.")
        return 2
      } catch(err) {
        console.log("err:", err.message)
        return 1
      } finally {
        console.log("Finally code performs ~, close operation")
        return 0
      }
      return 3
    }

    function test() {
        console.log(bar()) / / 0
    }

    test()
Copy the code

In ES10 (ES2019), the error bound after catch can be omitted.

Of course, if there is some code that must be executed, we can use finally to execute it. Finally represents the code structure that must eventually be executed.

Note: If there are return values in try,catch, and finally, then the return value in finally will be used.