the role of http://www.w3school.com.cn/js/js_onerror.asp Try...catch is to test for errors in the code.
JavaScript-Capturing errors
When we surf the web, we always see Javascript warning boxes with runtime errors, and ask us "Do you want to debug?" ”。 Error messages like this may be useful to developers, not to users. When errors occur, they often choose to leave the site.
This section explains how to capture and handle Javascript error messages, so you can provide more convenience to your audience.
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 an old-fashioned way to catch errors. (Netscape 3 later available)
Note: Chrome, opera, and Safari browsers do not support onerror events. Try ... Catch statement
Try...catch can test for errors in the code. The try section contains the code that needs to be run, and the Catch section contains the code that runs when the error occurs.
Code:<script type= "Text/javascript" >
var txt= ""
Function message ()
{
Try
{
Adddlert ("Welcome guest!")
}
catch (Err)
{
Txt= "There is an error on this page. \ n "
txt+= "Error Description:" + Err.Description + "\ n"
txt+= "Click OK to continue. \ n "
Alert (TXT)
}
}
</script>
The purpose of the throw declaration is to create a exception (exception or error).
Code:
<script type= "Text/javascript" >
var x=prompt ("Enter a number between 0 and ten:", "")
try< /c3>{ if (x>10) throw "Err1" else if (x<0) throw "Er R2 "}catch (er){ if (er==" Err1 ") alert (" error! The value is too high ") if (er = =" Err2 ") alert (" error! The value is too low ")}</script>
using the OnError event is an old-fashioned standard method of capturing Javascript errors in a Web page.
<script type= "Text/javascript" >
OnError = Handleerr
var txt = ""
function Handleerr (msg,url,l)
{
//handle the error here
Txt= "There are errors in this page. \ n "
txt+= "Error:" + msg + "\ n"
txt+= "url:" + URL + "\ n"
txt+= "line:" + L + "\ n"
txt+= "click" OK "to continue. \ n "
Alert (TXT)
return True
}
Function message ()
{
Adddlert ("Welcome guest!")
}
</script>
JavaScript exception Basic Syntax