How to handle JavaScript exception
How to handle JavaScript exceptions, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
Exception handling statements in js
There are two exception handling statements in js, one is try. Catch... One is throw.
Try... Catch is used for syntax errors, which have two attributes, name and message. Throw is used for logic errors.
Js does not throw an exception for logic errors, that is, it is useless to use trycatch. In this case, you need to create an instance of the error object yourself, and then use throw to throw an exception.
Exception handling in js uses the
(1) try. Catch... General use of
Error content: charAt () is lowercase
Copy the code
1try {
2varstre = "0123"
3console.log (str.charat (2))
4} catch (exception) {
5console.log ("name attribute-- >" + exception.name); / / name attribute-- > TypeError
6console.log ("message attribute-- >" + exception.message); / / message attribute-- > str.charatisnotafunction
7}
Copy the code
(2) try. Catch... Unable to catch logic error
Error content: Divisor cannot be 0
Copy the code
Try {
Varnum=1/0
Console.log (num); / / Infinity
} catch (exception) {
Console.log (exception.message)
}
Copy the code
(3) to throw an exception with throw, you need to instantiate an error by yourself.
Note: throw initializes an Error,E in uppercase with the new keyword. At the same time, this Error is the message property in the exception!
Copy the code
Try {
Varnum=1/0
If (num=Infinity) {
ThrownewError ("Error uppercase, initialize with new-> Divisor cannot be 0")
}
}
Catch (exception) {
Console.log (exception.message)
}
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.