JavaScript Try...catch ... Statement

Source: Internet
Author: User

When we use JavaScript for program development, we inevitably encounter a variety of errors: variable undefined, null value access, attribute not present, etc. because JavaScript is interpreted, there are some spelling mistakes that are more unlikely to be found before running, So how do you deal with so many kinds of javascript errors?

When an error occurs, the JavaScript engine stops and throws an error that contains an error message. In JavaScript, we can use Try...catch ... Statement to capture these error messages.

Try...catch ... Statement

The try statement allows us to define a block of code that performs error testing at execution time.

The catch statement allows us to define a block of code that executes when a try block of code has an error.

The try and catch in JavaScript are paired, otherwise they will cause a syntax error!

Grammar
Try {    // Run code here }catch  (err) {    ///  Handling Errors Here }

In the following example, we deliberately write an undefined function in the code of the try block, the catch block catches the error in the try block, and executes the code to handle it.

<!DOCTYPE HTML><HTML><Head>    <Script>        vartxt= ""; functionmessage () {Try{showmessage ("Hi there!"); }            Catch(err) {txt= "An error has occurred \ nyou"; TXT+= "Error Description:" +Err.message+ "\ n";            alert (TXT); }        }    </Script></Head><Body>    <inputtype= "button"value= "View message"onclick= "message ()"></Body></HTML>

JavaScript Try...catch ... Statement

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.