use
Typically, if an error occurs, the script stops immediately and prints out the error on the console.
With this statement, you can catch errors and take reasonable action, allowing the program to continue
grammar
Try {// code... } catch (err) {// Err is the object of error details // error catching, the above code will be referred to this block of code, and will not stop running} finally {// It always executes whether or not an exception is thrown or caught}Copy the code
Such statements can be nested
In field
Catch catches all errors.
If we don’t know what to do with it, we throw Err.
The throw operator generates an error object.
To throw a user-defined exception. Execution of the current function is stopped (statements after the throw will not execute), and control is passed to the first Catch block in the call stack. If there is no catch block in the caller function, the program terminates.
Example:
throw "Error1"; // An exception with a string value was thrown
throw 4; // An exception is thrown with the integer 4
/*JavaScript has many built-in standard error constructors: error, SyntaxError, ReferenceError, TypeError, etc. We can also use them to create error objects. * /
let error = new Error("Things happen o_O");
alert(error.name); // Error
alert(error.message); // Things happen o_O
/ / json exception
try {
JSON.parse("{ bad json o_O }");
} catch(e) {
alert(e.name); // SyntaxError
alert(e.message); // Unexpected token b in JSON at position 2
}
Copy the code
Add: The try block code may throw three types of exceptions: TypeError, RangeError, and SyntaxError
For those of you who don’t know what these three mean, let me explain
Both of these are global objects, and the global object itself does not contain any methods, yet it inherits some methods through the stereotype chain.
The instanceof operator is used to determine the type of error
TypeError :(TypeError) an error that occurs when an object is used to indicate that the type of a value is not the expected type
RangeError: The object indicates an error when a value is not in its allowed range or collection
SyntaxError: When the Javascript language parses the code, the Javascript engine throws tokens or tokens in an order that does not comply with the syntax
Example:
catch (e) {// The following are the object's parameter properties
console.log(e instanceof TypeError); // true
console.log(e.message); // "Describe this error"
console.log(e.name); // "TypeError"
console.log(e.fileName); // "The name of the file in which the code causing the exception resides"
console.log(e.lineNumber); // The line number of the code that caused the exception
}
Copy the code
- Male _ no. ❤; Front-end honest person, you can exchange and learn with small partners!