Fully understand the error handling mechanism in javascript and fully understand javascript

Source: Internet
Author: User

Fully understand the error handling mechanism in javascript and fully understand javascript

Previous

Error handling is critical to web application development. errors that may occur cannot be predicted in advance, and recovery policies cannot be taken in advance, which may lead to poor user experience. Because any javascript error may make the webpage unusable, as a developer, you must know when, why, and what errors may occur. This article describes in detail the error handling mechanism in javascript.

Error object 

An error object is an object that contains error information and a native object of javascript. When an error occurs during code parsing or running, the javascript engine will automatically generate and throw an error object instance, and the entire program will be interrupted where an error occurs.

console.log(t);//Uncaught ReferenceError: t is not defined

The ECMA-262 specifies that the error object contains two attributes: message and name. The message property stores the error message, while the name property stores the error type.

// Generally, try {t;} catch (ex) {console. log (ex. message); // t is not defined console. log (ex. name); // ReferenceError}

The browser also extends the attribute of the error object and adds other relevant information. The most implemented by browser vendors is stack attributes, which indicate stack tracing information (not supported by safari)

try{  t;}catch(ex){  console.log(ex.stack);//@file:///D:/wamp/www/form.html:12:2} 

Of course, you can use the error () constructor to create error objects. If the message parameter is specified, the error object uses it as its message attribute. If this parameter is not specified, it uses a predefined default string as the value of this attribute.

New Error (); new Error (message); // In general, throw statements are used to throw the Error throw new Error ('test'); // Uncaught Error: testthrow new Error (); // Uncaught Error
function UserError(message) {  this.message = message;  this.name = "UserError";}UserError.prototype = new Error();UserError.prototype.constructor = UserError;throw new UserError("errorMessage");//Uncaught UserError: errorMessage

When an Error () constructor is called like a function without the new operator, its behavior is the same as that when the new operator is called.

Error();Error(message);  throw Error('test');//Uncaught Error: testthrow Error();//Uncaught Error

The error object has a toString () method, and 'error: '+ message attribute of the Error object is returned.

var test = new Error('testError');console.log(test.toString());//'Error: testError'

Error Type 

There are multiple types of errors that may occur during code execution. Each type of error has a corresponding error type. When an error occurs, an error object of the corresponding type is thrown. The ECMA-262 defines the following 7 error types:

ErrorEvalError (eval error) RangeError (Range Error) ReferenceError (reference error) SyntaxError (syntax error) TypeError (Type Error) URIError (URI error)

Among them, Error is the base type, and other Error types are inherited from this type. Therefore, all error types share the same set of attributes. Errors of the Error type are rare. If any, they are also thrown by the browser. The main purpose of this base type is to allow developers to throw custom errors.

[EvalError (eval error )]

If the eval function is not correctly executed, an EvalError is thrown. This error type no longer appears in ES5. It is retained only to ensure compatibility with the previous code.

[RangeError (Range Error )]

An error of the RangeError type is triggered when a value exceeds the corresponding range, including exceeding the array length range and exceeding the numerical value range.

new Array(-1);//Uncaught RangeError: Invalid array lengthnew Array(Number.MAX_VALUE);//Uncaught RangeError: Invalid array length(1234).toExponential(21);//Uncaught RangeError: toExponential() argument must be between 0 and 20(1234).toExponential(-1);////Uncaught RangeError: toExponential() argument must be between 0 and 20

[ReferenceError (reference error )]

When a nonexistent variable or an lvalue type error is referenced, A ReferenceError (reference error) is triggered)

a;//Uncaught ReferenceError: a is not defined1++;//Uncaught ReferenceError: Invalid left-hand side expression in postfix operation

[SyntaxError (syntax error )]

SyntaxError (syntax error) is thrown when the rule does not comply with the syntax)

// Variable name error var 1a; // Uncaught SyntaxError: Unexpected number // The brackets console. log 'hello' are missing); // Uncaught SyntaxError: Unexpected string

[TypeError (Type Error )]

If an unexpected type is stored in the variable or the method that does not exist is accessed, the TypeError type is incorrect. Although there are many causes of errors, the reason is that the variable type does not meet the requirements when performing a specific type of operation.

var o = new 10;//Uncaught TypeError: 10 is not a constructoralert('name' in true);//Uncaught TypeError: Cannot use 'in' operator to search for 'name' in trueFunction.prototype.toString.call('name');//Uncaught TypeError: Function.prototype.toString is not generic

[URIError (URI error )]

URIError is an error thrown When URI-related function parameters are incorrect. It mainly involves encodeURI (), decodeURI (), encodeURIComponent (), decodeURIComponent (), escape (), and scape SCAPE () these six functions

decodeURI('%2');// URIError: URI malformed

Error Event

Any errors that are not handled through try-catch will trigger the error event of the window object.

The error event can receive three parameters: the error message, the URL of the error, and the row number. In most cases, only the error message is useful, because the URL only gives the location of the document, and the line number indicates that the code line may come from either embedded JavaScript code or external files.

To specify the onerror event handler, you can use the DOM0-level technology or the standard format of DOM2-level events.

// DOM0-level window. onerror = function (message, url, line) {alert (message) ;}// DOM2 level window. addEventListener ("error", function (message, url, line) {alert (message );});

Whether the browser displays standard error messages depends on the onerror return value. If the returned value is false, the error message is displayed on the console. If the returned value is true, the error message is not displayed.

// The error message window is displayed on the console. onerror = function (message, url, line) {alert (message); return false ;}a; // the error message window is not displayed on the console. onerror = function (message, url, line) {alert (message); return true;};

This event handler is the last line of defense against browser reporting errors. Ideally, it should not be used as long as it is possible. As long as the try-catch statement can be properly used, no errors will be handed over to the browser, and no error event will be triggered.

Images also support error events. An error event is triggered as long as the URL in the image's src feature cannot return a recognizable image format. In this case, the error event follows the DOM format and an event object with the image as the target will be returned.

A warning box is displayed when image loading fails. When an error occurs, the image download process is completed, that is, the image cannot be downloaded again.

var image = new Image();image.src = 'smilex.gif';image.onerror = function(e){  console.log(e);}

Throw statement and throw Error 

Throw statements are used to throw errors. When an error is thrown, you must specify a value for the throw statement.

[Note] the process of throwing an error is blocked, and subsequent code will not be executed.

throw 12345;throw 'hello world';throw true;throw {name: 'javascript'};

You can use the throw statement to manually throw an Error object.

throw new Error('something bad happened');throw new SyntaxError('I don\'t like your syntax.');throw new TypeError('what type of variable do you take me for?');throw new RangeError('sorry,you just don\'t have the range.');throw new EvalError('That doesn\'t evaluate.');throw new URIError('URI, is that you?');throw new ReferenceError('you didn\'t cite your references properly');

The prototype chain can also be used to inherit the Error to create a custom Error type (the prototype chain is described in Chapter 6th ). In this case, you must specify the name and message attributes for the newly created error type.

The browser treats custom Error types inherited from errors, just like other Error types. It is useful to create custom errors if you want to capture and treat them differently from browser errors.

function CustomError(message){  this.name = 'CustomError';  this.message = message;}CustomError.prototype = new Error();throw new CustomError('my message');

When a throw statement is encountered, the Code immediately stops execution. The code will continue to be executed only when a try-catch statement captures the thrown value.

In more detail, when an exception is thrown, The javascript interpreter immediately stops the logic currently being executed and jumps to the nearest exception handler. The exception handling program is written in the catch clause of the try-catch statement. If the code block that throws an exception does not have an associated catch clause, the interpreter checks the higher-level closed code block to see if it has an associated exception handler. And so on until an exception handler is found. If the function that throws an exception does not process its try-catch statement, the exception will be propagated up to the code that calls the function. In this way, the exception will be propagated up along the lexical structure and call stack of the javascript method. If no exception handling program is found, javascript treats the exception as a program error and reports it to the user.

Try catch statements and catch errors 

ECMA-262 3rd introduces try-catch statements as a standard way to handle exceptions in JavaScript, used to capture and handle errors

The try clause defines the code block of the exception to be processed. When an exception occurs somewhere in the try block after the catch clause follows the try clause, the Code logic in the catch is called. The catch clause follows the finally block, and the cleanup code is placed in the latter. The logic in the finally block is always executed no matter whether exceptions occur in the try block. Although both catch and finally are optional, the try clause must contain at least one of them to form a complete statement.

Try/catch/finally statement blocks must be enclosed by curly brackets. curly brackets are required here, even if there is only one statement in the clause

Try {// generally, the code here will not cause any problems from start to end // but sometimes it will throw an exception, or it will be directly thrown by the throw statement, either by calling a method to indirectly throw} catch (e) {// when and only when the try statement block throws an exception, the code here will be executed. // you can use the local variable e to obtain references to the Error object or other thrown values. // The code block here can handle this exception for some reason, you can also ignore this exception. You can also use the throw statement to throw the exception again} finally {// no matter whether the try statement throws an exception, the finally logic will always be executed, try statement block termination Methods: // 1. Normal termination, run the last statement of the statement block // 2. Terminate the statement through the break, continue, or return statement // 3. Throw an exception, exception caught by catch clause // 4. Throw an exception. The exception is not caught and continues to spread upwards}

Generally, all codes that may throw errors are placed in the try statement block, and the codes used for error handling are placed in the catch Block.

If an error occurs in any code in the try block, the Code Execution Process is immediately exited and the catch Block is executed. At this point, the catch block will receive an error message object, the actual information contained in this object will vary with the browser, but there is a message attribute that stores the error message.

[Note] You must name the error object. If you leave it blank, a syntax error is returned.

try{  q;}catch(error){  alert(error.message);//q is not defined}//Uncaught SyntaxError: Unexpected token )try{  q;}catch(){  alert(error.message);}

Catch accepts a parameter, indicating the value thrown by the try code block.

function throwIt(exception) { try {  throw exception; } catch (e) {  console.log('Caught: '+ e); }}throwIt(3);// Caught: 3throwIt('hello');// Caught: hellothrowIt(new Error('An error happened'));// Caught: Error: An error happened

After an error is captured in the catch code block, the program will not be interrupted and will continue to be executed according to the normal process.

Try {throw "error";} catch (e) {console. log (111);} console. log (222); // 111 // 222

To capture different types of errors, you can add judgment statements to the catch code block.

try { foo.bar();} catch (e) { if (e instanceof EvalError) {  console.log(e.name + ": " + e.message); } else if (e instanceof RangeError) {  console.log(e.name + ": " + e.message); } // ...}

Although the finally clause is optional in the try-catch statement, once the finally clause is used, its code will be executed in any way. In other words, the code in the try statement block is executed normally, and the finally clause is executed. If the catch statement block is executed due to an error, the finally clause will still be executed. As long as the Code contains a finally clause, No matter what code -- or even return statement contained in the try or catch statement block, the execution of the finally clause is not blocked.

// The error is not captured because no catch statement block exists. After the finally code block is executed, the program stops function cleansUp () {try {throw new Error ('Error ...... '); Console. log ('this row will not execute ');} finally {console. log ('finished cleanup work') ;}} cleansUp (); // The cleanup is completed. // Error: An Error occurred ......
function testFinnally(){  try{    return 2;  }catch(error){    return 1;  }finally{    return 0;  }}testFinnally();//0

[Note] the count value of the return Statement is obtained before the finally code block is run.

var count = 0;function countUp() { try {  return count; } finally {  count++; }}countUp();// 0console.log(count);// 1
Function f () {try {console. log (0); throw "bug";} catch (e) {console. log (1); return true; // this sentence will be delayed until the finally code block ends and then run console. log (2); // does not run} finally {console. log (3); return false; // This statement overwrites the previous return console. log (4); // does not run} console. log (5); // will not run} var result = f (); // 0 // 1 // 3console. log (result); // false

[Tips] block-level scope

A common purpose of a try-catch statement is to create block-level scopes. The declared variables are valid only within the catch.

ES6 introduces the let keyword to create a block-level scope for the declared variables. However, in ES3 and ES5, try-catch statements are often used to achieve similar results.

The following code shows that e only exists in the catch clause. An error is thrown when you try to reference it elsewhere.

Try {throw new Error (); // throw an Error} catch (e) {console. log (e); // Error (...)} Console. log (e); // Uncaught ReferenceError: e is not defined

The core of common error handling is to first know what errors will occur in the code. Because javaScript is loose and does not validate function parameters, errors only occur during code. Generally, you need to pay attention to three types of errors: type conversion errors, data type errors, and communication errors.

[Type conversion error]

A type conversion error occurs when an operator is used, or when other language structures of data types that may automatically convert values are used.

A throttling statement is a frequent type conversion error. Statements such as if automatically convert any value to a Boolean value before determining the next operation. Especially if statements, if used improperly, are the most error-prone.

The undefined value is automatically assigned to unused naming variables. The undefined value can be converted to a Boolean value of false. Therefore, the if statement in the following function is only applicable when the third parameter is provided. The problem is that not only undefined can be converted to false, but not only string values can be converted to true. For example, if the third parameter is a value of 0, the test of the if statement will fail, and the test of the value 1 will pass

Function concat (str1, str2, str3) {var result = str1 + str2; if (str3) {// This is definitely not the result + = str3;} return result ;}

Using non-boolean values in a flow control statement is a very common error source. To avoid such errors, a Boolean value must be input during condition comparison. In fact, executing some form of comparison can achieve this goal.

Function concat (str1, str2, str3) {var result = str1 + str2; if (typeof str3 = 'string') {// more suitable result + = str3 ;} return result ;}

[Data Type Error]

Javascript is loose, so they are not compared before using variables and function parameters to ensure that their data types are correct. To avoid data type errors, you can only write appropriate data type detection code. When unexpected values are passed to the plotting function, data type errors are most likely to occur.

// Unsafe function. Any non-array value will cause the function reverseSort (values) {if (values) {values. sort (); values. reverse ();}}

Another common error is comparing a parameter with a null value. Comparing with null can only ensure that the corresponding values are not null and undefined. To ensure that the input value is valid, it is not enough to detect null values only.

// Unsafe function. Any non-array value will cause the function reverseSort (values) {if (values! = Null) {values. sort (); values. reverse ();}}

If an object (instead of an array) containing the sort () method is passed in, an error may occur when calling the reverse () function.

// Unsafe function. Any non-array value will cause the function reverseSort (values) {if (typeof values. sort = 'function') {values. sort (); values. reverse ();}}

When you know exactly what type should be passed in, it is best to use instanceof to check its data type.

// Security. function reverseSort (values) {if (values instanceof Array) {values. sort (); values. reverse ();} is ignored for non-Array values ();}}

[Communication error]

With the rise of Ajax programming, it has become common for Web applications to dynamically load information or functions in their lifecycles. However, any communication between javascript and the server may produce errors.

The most common problem is that encodeURIComponent () is not used to encode the data before it is sent to the server.

// Error http://www.yourdomain.com /? Redir = http://www.sometherdomain.com? A = B & c = d // For all strings after 'redir = 'Call encodeURIComponent () to solve this problem http://www.yourdomain.com /? Redir = http: % 3A % 2F % 2Fwww.sometherdomain.com % 3Fa % db % 26c % 3Dd

The above Article fully understands the error handling mechanism in javascript, that is, all the content that I have shared with you. I hope you can give me a reference and support me a lot.

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.