In JavaScript you can use Try...catch to do exception handling. For example:
Try {
Foo.bar ();
Catch (e) {
":" + e.message);
}
The system anomalies we may get at the moment mainly include the following 6 types:
- Evalerror: Raised when a error occurs executing code in eval ()
- Rangeerror: Raised when a numeric variable or parameter are outside of its valid range
- Referenceerror: Raised when de-referencing an invalid reference
- SyntaxError: Raised when a syntax error occurs and parsing code in eval ()
- TypeError: Raised when a variable or parameter are not a valid type
- Urierror: Raised when encodeURI () or decodeURI () is 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 methods for throwing exceptions manually are as follows:
Try {
Throw New Error ("whoops!");
Catch (e) {
":" + e.message);
}
To determine the type of exception information, you can judge it in a catch:
try {
Foo.bar ();
} Span class= "Java-keyword" > catch (e) {
if (E instanceof evalerror) {
Alert (e.name + + e.message);
}
else if (e instanceof rangeerror) {
Alert (e.name + + e.message);
}
//etc
}
Error has some of the following main properties:
- Description: Error description (ie only available).
- FileName: The file name of the error (only Mozilla is available).
- LineNumber: Number of rows in error (only Mozilla is available).
- Message: Error message (description in IE)
- Name: the error type.
- Number: Error code (IE is available only).
- 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 part to the following form:
Try{
Foo.bar ();
}Catch(e) {
if(BrowserType! = Browser_ie) {
Alert "name:" + e.name +
"message:" + e.message +
" LineNumber: " + e.linenumber +
" FileName: " + E.filename +
+ e.stack);
}
else {
Alert ( "name:" + e.name +
+ (E.number & 0xFFFF) +
" message: " + e.message");
}
}
The throw command in JavaScript can actually throw any object, and we can accept that object in a catch. For example:
Try {
Throw New
Catch (e) {
}
Original: http://www.scdyl.com/blo/post/263.html
Try...catch and exception handling in JavaScript