In JavaScript, you can use Try...catch for exception handling. For example:
Copy Code code as follows:
try {foo.bar ();} catch (E) {alert (e.name + ":" + E.message);}
At present, we may get the system anomaly mainly contains the following 6 kinds:
evalerror:raised when a error occurs executing code in eval ()
rangeerror:raised when a numeric variable or parameter be outside of its valid range
referenceerror:raised when de-referencing a invalid reference
syntaxerror:raised when a syntax the error occurs while parsing the code in eval ()
typeerror:raised when a variable or parameter are not a valid type
urierror:raised when encodeURI () or decodeURI () are passed invalid parameters
All six of the above exception objects inherit from the Error object. They all support the following two methods of construction:
New error (); New error ("Exception information");
The way to throw exceptions manually is as follows:
Copy Code code as follows:
Try {throw new Error ("whoops!");} catch (E) {alert (e.name + ":" + E.message);}
To determine the type of exception information, you can judge in a catch:
Copy Code code as follows:
try {foo.bar ();} catch (E) {if (e instanceof evalerror) {alert (e.name + ":" + E.message);} else if (e instanceof rangeerror) {alert (e.name + ":" + E.message);} ETC}
The error has some of the following main properties:
Description: Error description (ie only available).
FileName: The file name of the error (Mozilla only available).
LineNumber: The number of rows that failed (Mozilla only available).
Message: Error messages (in IE below description)
Name: Error type.
Number: Error code (ie only available).
Stack: Error stack information like stack trace in Java (only Mozilla is available).
So in order to better understand the error message, we can change the catch section to the following form:
Copy Code code as follows:
try {foo.bar ();} catch (E) {if (BrowserType!= browser_ie) {
Alert ("Name:" + e.name + "message:" + E.message + "linenumber:" + E.linenumber + "FileName:" + E.filename + "stack:" + E.stack);
} else {
Alert ("Name:" + e.name + "ErrorNumber:" + (E.number & 0xFFFF) + "message: + E.message");
} }
The throw command in JavaScript can actually throw any object, and we can accept this object at catch. For example:
Copy Code code as follows:
try {throw new date ();//Throw Current Time object} catch (e) {alert (e.tolocalestring ());//show current time using local format}