JavaScript Advanced Programming Notes (17)

Source: Internet
Author: User

Error handling and debugging (a) the browser reported error 1. IE2. Firefox3.Safari4.Opera5.Chrome (ii) Error handling 1.try-catch statement
Try {    // may cause error in code }catch(error) {    //  What to do when an error occurs }

A catch receives an object containing an error message after an error, and it holds the messages property of the error.

①finally clause

Once the finally clause is used, its code executes anyway. IE7 and earlier bugs: The finally code will never execute unless there is a catch clause. As long as the code contains a finally clause, the return statement in either the try or catch statement block will be ignored.

② Error Type

Error: base type.

When the Evalerror:eval function is abnormal.

Rangeerror: When the value is out of range.

Referenceerror: The object was not found.

TypeError: A variable holds an unexpected type, or accesses a method that does not exist.

Urierror: The URI format is incorrect using encodeURI or decodeURI.

② Rational Use of Try-catch

Best for dealing with errors that we cannot control.

2. Throwing errors

The throw operator, which is used to throw a custom error at any time, to specify a value for it.

When the throw operator is encountered, the code stops executing immediately, and the code executes only if a Try-catch statement captures the thrown value.

The most common error types created when creating custom error messages are error, Rangeerror, Referenceerror, and TypeError.

① throw the wrong time

Throws an error when a specific known error condition causes the function to fail to execute properly.

② throwing errors with the use of Try-type

The goal of capturing errors is to prevent browsers from handling them by default, and the purpose of throwing errors is to provide a message that the error occurred for a specific reason.

3. Error events

The Error event handler captures the creation of the event object, but can accept three parameters: the error message, the URL where the error occurred, and the line number.

        function (message, URL, line) {            alert (message);             return false;  // default behavior that prevents browsers from reporting errors         };         Throw New Error ("Something bad happened.");

4. Strategies for handling errors

5. Common Types of errors

① Type Conversion Error

Occurs when an operator is used, or a language structure that uses other data types that may automatically convert values.

Use the = = and! = operators, or when using non-Boolean values in the If, for, and while flow control statements.

② Data Conversion Error

Comparisons with NULL only ensure that the corresponding values are many null or undefined.

The value of the base type should be detected with typeof, and the value of the object should be detected with instanceof.

③ Communication Error

Malformed URLs or data that occurs, the most common is that data is not encoded with encodeuricomponent () before it is sent to the server.

For query strings, you must use the encodeURIComponent () method.

6. Distinguishing between fatal and non-fatal errors

Non-fatal error: Does not affect the user's primary task, affects only part of the page, can repair, repeat the same action can eliminate the error.

Fatal error: The application cannot continue running at all, the error significantly affects the user's primary operation, and can lead to other joint errors.

When a fatal error occurs, a message should be sent to the user telling them that they cannot continue with the task.

7. Log the error to the server

Writes the error to the place where the server-side error was saved.

// get the data from the query string and write the data to the error log
Parameters: Severity of numeric or string and error messages, using an image object to send requests
function logError (SEv, msg) { varnew Image (); = "log.php?sev=" + encodeuricomponent (SEv) + "&msg=" + encodeURIComponent (msg);}

As long as the use of the Try-catch statement, it should be the corresponding error recorded in the log.

(iii) Commissioning technology 1. Logging messages to the console

The browser can output messages to the console through code. IE8, Firefox, Chrome, and Safari can write messages to the JavaScript console through the console object.

Method: Error () info () log () warn ()

Using LiveConnect

2. Log messages to the current page

Displays a message in a small area of the page.

3. Throwing errors

Custom errors are usually thrown using asert, which can accept two parameters: the condition that evaluates to true and the error to throw when the condition is false.

Replace the IF statement for some functions.

        function Divide (NUM1, num2) {            assert (typeoftypeof num2 = = "Number"                    ,"divide (): Both arguments must be numbers. " );             return NUM1/ num2;        }

(d) Common IE error 1. Termination of operation

Before IE8, an operation termination error occurs when the <script> node is contained in an element, and the JavaScript code uses appendchild (), innerHTML, or other DOM methods to modify the parent or ancestor elements of the element.

You can wait until the target element has finished loading and then manipulate it, or add an overlay to document.body that is absolutely positioned on the page.

// The new <div> element is added to the beginning of the document.body instead of the end, and the information to complete this section is known    when the script is run <div>        <script type= "Text/javascript" >                    document.body.insertBefore (document.createelement ("div"), document.body.firstChild);             </script>    </div>

You can also use the <script> element directly as a sub-element of <body>.

2. Invalid characters

For example a very similar minus sign is a character (\u2013) that has a Unicode value of 8211, and cannot be used as a regular minus sign. This character is usually inserted automatically in the Word document.

3. No members found

caused by a garbage collection routine mate error. Occurs when the re-redemption is destroyed and the object is assigned a value. The most common use of the event object is that the event object of IE has a window property, which is created when an event occurs and is destroyed after the last event handler has finished executing. If another closure uses the event object, and the closure does not execute immediately, a member error is not found when it is called in the future and assigns a value to the event's property.

function () {      var event = window.event;      SetTimeout (function() {          false;     // member error},1000 not found      );}

4. Unknown run-time error

When you specify HTML by using innerHTML or outerhtml: Insert a block element into an inline element to access any property of any part of the table

5. Syntax errors

6. The system cannot find the specified resource

Occurs when a resource URL is requested by using JavaScript that is longer than 2,083 characters.

JavaScript Advanced Programming Notes (17)

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.