introduce
In this article, the 18th in the advanced JavaScript tutorial, we will cover exception handling in JS
The body of the
1. Exception handling scheme
During development, we will encapsulate some utility functions and then make them available to others:
- During use, some parameters may be passed to the utility function
- For functions, we need to validate the parameters, otherwise we may not want the result
Most of the time, if the result is not what we want, we may directly return, but return has disadvantages:
- The caller does not know that the function did not execute properly and returns directly
undefined
- In fact, the right thing to do is to tell the outside world if you don’t pass some validation
// Let's write a utility function
function double(number) {
if (typeofnumber ! = ='number') {
return
}
return number * 2
}
// The argument was passed incorrectly
const doubleNumber = double('hello')
// 所以 doubleNumber 就是 undefined
// If no error is reported, the subsequent logic will still work, which is a drawback
Copy the code
So how do we tell the outside world:
- use
throw
To throw an exception
Throw statement:
- Use to throw a user-defined exception
- When a throw statement is encountered, the code after the throw is not executed
So throwing an error using a throw is the correct solution if the function fails some validation
// Then we can change it
function double(number) {
if (typeofnumber ! = ='number') {
// An error is thrown
throw new TypeError('Expected a number, bug got ' + typeof number)
}
}
const doubleNumber = double('hello')
// If the above code is not caught, the subsequent logic will not be executed
Copy the code
Throw keyword
A thorw expression is an expression that follows a throw to express specific exception information:
throw expression
What type does the throw keyword follow?
- Basic data types: number, String, Boolean
- Object types: Object types can contain more information
throw 1
throw "error"
throw false
throw {
errorCode: '2001'.msg: "error"
}
Copy the code
But it’s cumbersome to manually create an object each time, so we can encapsulate it as a class:
class MyError {
constructor(errorCode, errorMsg) {
this.errorCode = errorCode
this.errorMsg = errorMsg
}
}
throw new MyError("2001".'error')
Copy the code
3. The Error class
We throw an exception in JS that encapsulates a class:
throw new Error('error msg')
Copy the code
An Error instance contains three attributes:
message
: Parameter passed when creating the Error objectname
: Error Specifies the name of the instance, usually the same as the class namestack
: The entire Error message contains the call stack of the function. When we print the Error object directly, we print the stack
Error also has subclasses:
RangeError
: Error type used when an index value is out of boundsSyntaxError
: Error type used to parse syntax errorsTypeError
: Error type to use when a type error occurs
4. Catch exceptions
When we use a function, if the content of the function throws an exception, we need to catch the exception manually in order to ensure that the following code continues to run. Catch statement
try… Catch statement structure:
try {
try_statements
}
[catch (exception_var_1) {
catch_statements_1
}]
[finally {
finally_statements
}]
Copy the code
Sample:
function foo() {
throw new Error('error')}try {
foo()
} catch (error) {
console.log('error') // The exception from foo comes in here to be handled
} finally {
// finally is usually not written
console.log('always execute') // Whether there is an exception or not, this will be executed.
}
console.log('code') / / run
Copy the code
By the way, starting with ES10, catch can no longer write parameters
try{}catch{}Copy the code
conclusion
In this article, you learned:
- The correct way to handle function boundary cases is to throw an exception
- Throw a keyword
- Error and subclasses
- How to catch exceptions