You can use try...catch in JavaScript for exception handling. For example:
try { foo.bar();} catch (e) { alert(e.name ": " e.message);}
Currently, the system exceptions we may get mainly 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
Above The six exception objects all inherit from the Error object. They all support the following two construction methods:
new Error();new Error("Exception information");
The method of manually throwing exceptions is as follows:
try { throw new Error("Whoops!");} catch (e) { alert (e.name ": " e.message);}
If you want to determine the type of exception message, you can do it 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 main Properties:
description: Error description (only available in IE).
fileName: Error file name (only available in Mozilla).
lineNumber: Error line number (only available in Mozilla).
message: error message (same as description under IE)
name: error type.
number: error code (only available in IE).
stack: error stack information like Stack Trace in Java ( Only available in Mozilla).
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 "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 This object is received in catch. For example:
try { throw new Date(); // Throws the current time object} catch (e) { alert(e.toLocaleString()); // Use local format to display the current time}