How to use JavaScript try...catch statements

Source: Internet
Author: User

Try...catch can test errors in your code. The try section contains the code that needs to be run, and the catch part contains the code that runs when the error occurs.
There are two ways to catch errors in a Web page:
Use the Try...catch statement. (Available in ie5+, Mozilla 1.0, and Netscape 6)
Use the OnError event. This is the old-fashioned way to catch errors. (after Netscape 3 version available)
Note: Chrome, opera, and Safari browsers do not support onerror events.
Grammar

try{
Statement1
}catch (Exception) {
Statement2
}

Instance
<title>using a try. Catch statement</title>
<script language= "JavaScript" >
<!--
function MyErrorHandler (data) {
try{
try{
if (data = = "string") {
Throw "E0";
}else{
Throw "E1";
}
}catch (e) {
if (E = = "E0") {
Return ("Error (" + E + "): Entry must is numeric.");
}else{
Throw e;
}
}
}catch (e) {
Return ("Error (" + E + "): Entry is invalid.");
}
}
function ProcessData (form) {
if (isNaN (parseint (form.myText.value)) {
Alert (MyErrorHandler ("string"));
}else{
Alert ("You have correctly entered a number");
}
}
-->
</script>
<body>
<form name= "MyForm" >
Please enter a number:
<input type=text size=10 value= "name=" MyText ">
<input Type=button value= "Process" name= "MyButton" onclick= ' ProcessData (this.form) ' >
</form>
</body>

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.