Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to handle JavaScript exception

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report