JavaScript DHTML/Language Basics/throw

Материал из Web эксперт
Перейти к: навигация, поиск

Catch that error

   <source lang="html4strict">
  

<HTML> <HEAD> <TITLE>Catch that error!</TITLE> <SCRIPT> function catchError(errString) {

  try {
     try {
        if (errString == -1)
           throw new Error (-1, "errString is -1!");
        else
           throw new Error (0, "errString is NOT -1!");
     }
     catch(e) {
        if (e.number == -1)
           return (e.description + " Got this one!");
        else
           throw e;
     } 
  }
  catch (e){
     return(e.description + " This one not handled here!");
  } 

} </SCRIPT> </HEAD> <BODY> <FORM name="theForm"> <INPUT type=text name=errText value="-1"> <INPUT type=button name=btnThrow value="Catch it!" onClick="alert(catchError(document.theForm.errText.value));"> </FORM> </BODY> </HTML>


 </source>
   
  


Exception handling with try/catch

   <source lang="html4strict">
  

<HTML> <HEAD> <TITLE></TITLE> <SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript"> function getMonthName (monthNumber) {

    throw "InvalidMonthNumber"

} try {

   alert(getMonthName(13))

} catch (exception) {

   alert("An " + exception + " exception was encountered.  Please contact the program vendor.")

}

</SCRIPT> <BODY> </BODY> </HTML>


 </source>
   
  


Throws error in case of invalid data

   <source lang="html4strict">
 

<html> <head> <title>Try/Catch</title> </head> <body> <form name="formexample" id="formexample" action="#">

Enter a value: <input id="value" name="value">
<input id="submit" type="submit">

</form> <script type="text/javascript"> function checkValid() {

   try {
       var valueField = document.forms[0]["value"];
       if (valueField.value != "A") {
           throw "It"s not what I need";
       }
   }
   catch(errorObject) {
       alert(errorObject);
   }

} function init() {

   document.forms[0].onsubmit = function() { return checkValid() };

} window.onload = init; </script> </body> </html>


 </source>
   
  


Throw that error

   <source lang="html4strict">
  

<HTML> <HEAD> <TITLE>Throw that error!</TITLE> <SCRIPT> function throwError(errString) {

  try {
     throw new Error (42, errString);
  }
  catch(e){
     alert("Error number: " + e.number + "; Description: " + e.description)
  }   

} </SCRIPT> </HEAD> <BODY> <FORM name="theForm"> Error text: <INPUT type=text name=errText size=40> <INPUT type=button name=btnThrow value="Throw it!" onClick="throwError(document.theForm.errText.value);"> </FORM> </BODY> </HTML>


 </source>