In JavaScript, try... catch can be used for exception handling. For example:
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:
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:
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:
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 in catch. For example:
Try {Throw new date (); // throw the current time object} catch (e) {alert (E. tolocalestring (); // display the current time in local format}