Summary of javascript Exception Handling

Source: Internet
Author: User
Tags finally block try catch
Document directory
  • Try catch finally statement description
  • Throw statement description
  • Error object
  • Javascript Exception Handling Mechanism and window. onerror handle

You can use the try... catch... finally statement to handle exceptions in JavaScript, or manually throw exceptions.
1. Use the try... catch... finally statement to handle exceptions.
If an exception occurs during execution of js Code, an exception class object is manually created and submitted to the browser. This process is called "throwing an exception ". When the browser receives an object, it looks for code that can handle this exception and submits the current exception object to it for processing. This process is called "capturing exceptions ". The basic syntax format of try... catch... finally statements is: Copy codeCode: try {// code that may throw an exception
} Catch (error) {// code executed if an exception occurs. error is an exception class object.
} Finally {// unconditionally executed code
}

In the preceding statement, the catch statement is followed by the try statement, and the finally statement is followed by the catch statement. This is a complete statement for exception handling. In fact, both the catch statement and the finally statement can be omitted, but at least one of them must be used in combination with the try statement.
The statement in the try block does not have to throw an exception. Any JavaScript statement can be processed using an exception handling statement, but this is not necessary. If an exception is thrown in a line of code in the try block, the code below the line will not be executed, and the catch Block Code will be executed directly.
In the catch Block, the error in the brackets following the catch statement indicates the caught exception object instance. This instance contains detailed information about the exception and can be properly handled based on the information. If there is a finally statement after the catch statement, continue to execute the statement in the finally block.
The statements in the finally block are always executed. The statements in the block are usually cleaned up. If a transfer statement, such as return statement, continue statement, or break statement, is encountered before the finally block is executed, the code in the finally block will also be executed before the statements are executed.
If an exception handling statement contains only try .. if a catch statement does not have a replenishment exception, the finally BLOCK statement is executed directly after the statement in the try block is executed, and then the exception is thrown.
Example:Copy codeThe Code is as follows: <script>
Try {
Var date = new Date ();
Date. test (); // call date's undefined test method;
Document. wrire ("try block execution ended <br> ");
} Catch (error ){
With (document ){
Write ("an exception occurred <br> ");
Write ("exception type:" + error. name + "<br> ");
Write ("exception message:" + error. message );
}
} Finally {
Document. write ("exception handling is complete! ");
}
</Script>

Result:
An exception occurred.
Exception type: TypeError
Exception message: the object does not support this attribute or the method has completed exception handling!
2. Manually throw an exception
In addition to the exception thrown by the browser during running, developers can also throw the exception by themselves. The throw statement is thrown when a manual exception occurs. Its basic syntax format is:
Throw expression;

Try catch finally statement description

Try catch finally is an exception handling mechanism provided by the javascript language. The syntax structure is as follows:

Try {// This code runs from top down. If any of the statements throws an exception, the code block stops running.
} Catch (e) {// if an exception is thrown in the try code block, the code in the catch code block will be executed. // E is a local variable used to point to the Error object or other thrown objects} finally {
// The finally code block will always be executed no matter whether the code in the try has an exception thrown (or even the return statement in the try code block. }

Try... Catch... Finally... In the syntax, except try, catch and finally are both optional (both must have one), that is, try... Catch... Finally... The syntax has the following three forms:

Try {

// Some code

}

Catch (e ){

// Somecode

}

Finally {

// Some code

}

Try {

// Some code

}

Catch (e ){

// Somecode

}

Try {

// Some code

}

Finally {

// Some code

}

If there is a catch, once the code in try throws an exception, the code in catch is executed first, and then the code in finally is executed. If no catch statement exists, after the code in try throws an exception, the finally statement is executed first, and the exception thrown in try continues to be thrown in the exception manner.

No matter how the execution of the try code block is terminated (exceptions, return, and natural termination occur), The finally statements are always executed. It is precisely because of this feature of finally, usually finally is used to perform some cleanup work. If the code in try is terminated in the return, continue, and break mode, the Javascript engine will execute the return statement in try after the finally statement is executed.

Throw statement description
The throw statement has been implemented in javascript1.4. The try syntax is very simple, as follows:
throw expression;

The expression can be of any type, that is, throw "There is a error" or throw 1001 is correct. However, we usually throw an Error object or a subclass of the Error object. For more information about Error, see the sample code of throw.

function factorial(x) { // If the input argument is invalid, throw an exception! if (x < 0) throw new Error("x must not be negative"); // Otherwise, compute a value and return normally for(var f = 1; x > 1; f *= x, x--) /* empty */ ; return f;}
Error object

The Error object and its subclass are implemented in javascript1.5. Error constructor has two types:

new Error( )
new Error(message )

Error has two basic attributes: name and message. Message is used to indicate detailed information about an exception. Name indicates the constructor of the Error object. In addition, different js engines provide some extensions for Error, such as mozilla providesFileName (abnormal file name) and linenumber (abnormal row number) Extension, While IE provides number (error number) support. However, name and message are two basic attributes that can be supported in firefox and ie. There are several subclasses of Error in Javascript.EvalError,RangeError,ReferenceError,SyntaxError,TypeError,The meaning of URIError is not described in detail here. You can find the reference in the reference document provided by me.

Javascript Exception Handling Mechanism and window. onerror handle

When an error occurs in javascript code, the js engine will find the corresponding catch step by step based on the js call stack, if the corresponding catch handler or catch handler is not found, and an error exists or a new error is thrown, the error is finally handled by the browser, the browser displays the error information to visitors in different ways (IE is displayed in the lower left corner with a yellow triangle, while firefix is displayed in the error console. In many scenarios, we may feel that this error prompt method is not friendly enough and the prompt information is concealed. Do we have the opportunity to customize this error prompt method? The answer is: window. onerror.

The window object of javascript has a special attribute onerror. If you assign a function to the onerror attribute of window, the function will be called if any javascript error occurs in the window, that is to say, this function will become the error handling handle of this window.

// Display error messages in a dialog box, but never more than 3window.onerror = function(msg, url, line) { if (onerror.num++ < onerror.max) {  alert("ERROR: " + msg + "\n" + url + ":" + line);  return true; }}onerror.max = 3;onerror.num = 0;

The onerror handle prompts three parameters, namely the error message, generating the document ulr of the wrong javascript, And the row number of the error.

The Return Value of the onerroe handle is also very important. If the handle returns true, it means that the browser does not need to handle the error, that is, the browser does not need to display the error message. If false is returned, the browser still prompts an error message.

Window. onerror = function (){

Alert ("xx ");

Return true; // If you comment out this statement, an error message will still be prompted in the browser. Otherwise, no.

}

Function throwerror (){

Throw new Error ("cc ");

}

We cannot avoid Js exceptions during HTML development. Normally, we cannot rely on the client to open the browser error prompt box (for example) to provide clues for us to locate bugs, and use window. the onerror handle is displayed as an error prompt. When an error occurs, the customer can provide screenshots. This helps developers locate the issue, analyze javascript-related errors.

References

Mozilla Javascript1.5 core reference

Javascript rhino (JavaScript: The Definitive Guide)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.