1. Use window.onerror to specify the error handling function. When there is an error, onerror will be called back. When there are multiple script errors in a JavaScript block, after the first error is triggered (callback), the scripts following the current JavaScript block will be automatically dropped and ignored, and will not be executed.
For example:
In the above example, only the first test(); in each block will generate an error. When the window.onerror callback is triggered, the following Javascript will be ignored. img also supports onerror < img src="pic.gif" onerror = "javascript:alert("An error occurred.");"/>. onerror is an object supported by the browser. It is up to the browser to decide whether it can be used, not the DOM standard.
2. Use try catch throw in Javascript to handle exceptions. Javascript supports try catch throw, exceptions defined in Javascript:
(1)EvalError: An error occurs in the eval() function.
(2)RangeError: A number value is greater then or less then the number that can be represented in Javascript(Number.MAX_VALUE and Number.MIN_VAKUE).
(3)ReferenceError: An illegal reference is used.
(4)SyntaxError: A syntax error occus inside of an eval() function call. All other syntax error are reorted by the browser and cannot be handled with a try...catch statement.
(5)TypeError. A variables type is unexpected. 6.URIError. An error ocuurs in the encodeURI() or the decodeURI() function.
For example:
Error.message is a property supported by both IE and FireFox.
IE supports description and number attributes.
FF supports fileName lineNumber and stack attributes.
Because Javascript is a weakly typed language.
So you can only catch once in the catch part. You cannot write multiple catches like C# to catch different types of exceptions.
But you can use instanceof ErrorType to achieve similar functions.
For example:
Note: The browser will not throw an Error type exception, so if an Error type exception is caught, it can be determined that the exception is thrown by the user code, not the browser.
Javascript assert()
function assert(bCondition, sErrorMsg) {
if (!bCondition) {
alert(sErrorMsg);
throw new Error(sErrorMsg);
}
}