JavaScript error
JavaScript Errors - throw, try, and catch
try statements test for errors in blocks of code.
catch statement processing error.
throw statement creates a custom error.
JavaScript Error
When the JavaScript engine executes JavaScript code, various mistake.
may be a syntax error, usually a coding error or typo made by the programmer.
could be a spelling mistake or a missing feature in the language (possibly due to browser differences).
The error may be caused by incorrect output from the server or user.
Of course, it may also be due to many other unpredictable factors.
JavaScript throws an error
When When an error occurs, when something goes wrong, the JavaScript engine usually stops and generates an error message.
The technical term to describe this situation is: JavaScript will throw an error.
##JavaScript try and catch
try Thestatement allows us to define blocks of code that are tested for errors when executed.
catchstatement allows us to define the code block that is executed when an error occurs in the try code block.
JavaScript statementstryandcatchappear in pairs.
Syntax
try {//Run the code here
} catch(err) {
//Handle errors here
}
Example
In the following example, we intentionally There is a typo written in the code of the try block. Intentionally writing the alert as addlertRun the program to try itphp中文网(php.cn)
Throw statement
The throw statement allows us to create custom errors. The correct technical term is: creating or throwing an exception.If you use throw with try and catch, you can control the program flow and generate custom error messages.
Syntax
throw exception
Exception can be JavaScript string, number, logical value or object.
Example
This example detects the value of the input variable. If the value is wrong, an exception (error) is thrown. catch will catch this error and display a custom error message:
php中文网(php.cn) 我的第一个 JavaScript
请输出一个 5 到 10 之间的数字:
Run the program and try it
Note, if the getElementById function makes an error, the above The example will also throw an error.