In JavaScript, try... catch can be used for exception handling. For example:
Copy codeThe Code is as follows:
Try {foo. bar ();} catch (e) {alert (e. name + ":" + e. message );}
Currently, the possible system exceptions include the following 6 types:
EvalError: raised when an error occurs executing code in eval ()
RangeError: raised when a numeric variable or parameter is outside of its valid range
ReferenceError: raised when de-referencing an invalid reference
SyntaxError: raised when a syntax error occurs while parsing code in eval ()
TypeError: raised when a variable or parameter is not a valid type
URIError: raised when encodeURI () or decodeURI () are passed invalid parameters
The preceding six exception objects are inherited from Error objects. They both support the following two constructor methods:
New Error (); new Error ("exception information ");
The method for manually throwing an exception is as follows:
Copy codeThe Code is as follows:
Try {throw new Error ("Whoops! ");} Catch (e) {alert (e. name +": "+ e. message );}
To determine the type of the exception information, you can make a judgment in catch:
Copy codeThe Code is 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}
Error has the following attributes:
Description: Error description (IE only ).
FileName: indicates the file name with an error (available only for Mozilla ).
LineNumber: Number of wrong lines (available only for Mozilla ).
Message: error message (description in IE)
Name: Error type.
Number: Error Code (IE only ).
Stack: Error Stack information similar to the stack Trace in Java (available only by Mozilla ).
Therefore, to better understand the error information, we can change the catch part to the following form:
Copy codeThe Code is 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 & 0 xFFFF) + "message:" + e. message ");
}}
The throw command in JavaScript can actually throw any object, and we can accept this object in catch. For example:
Copy codeThe Code is as follows:
Try {throw new Date (); // throw the current time object} catch (e) {alert (e. toLocaleString (); // display the current time in local format}