JavaScript Tutorial/Development/Error

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

Catch an error (IE)

   <source lang="javascript">

<HTML> <HEAD>

  <TITLE>Catch that error!</TITLE>

<SCRIPT> function catchError(errString) {

  try {
     try {
           throw new Error (42, "errString is 42!");
     }
     catch(e) {
        if (e.number == 42)
           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 size=40 value="42"> <INPUT type=button

      name=btnThrow 
      value="Catch it!" 
      onClick="alert(catchError(document.theForm.errText.value));">

</FORM> </BODY> </HTML></source>


Throw out an Error

   <source lang="javascript">

<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"> Enter text for the error: <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>


Try catch user exception

   <source lang="javascript">

<html> <head> <title>Try Catch Example</title> <script type="text/javascript"> function addTwoNumbers(a, b) {

   throw new Error("Two numbers are required.");

} try {

   result = addTwoNumbers(90);

} catch (oException) {

   alert(oException.message);

} </script> </head> <body> </body> </html></source>


Use Error

   <source lang="javascript">

<html> <head> <title>Try Catch Example</title> <script type="text/javascript"> function addTwoNumbers(a, b) {

   throw new Error("Two numbers are required.");

} try {

   result = addTwoNumbers(90);

} catch (oException) {

   alert(oException.message);

} </script> </head> <body> </body> </html></source>