JavaScript Tutorial/Statement/try catch

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

Catch that error

<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>


Exception handling with try/catch

<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>


try...catch

Syntax



try{
        statement1
    }catch(exception){
        statement2
    }