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>