A comprehensive understanding of error-handling mechanisms in JavaScript _javascript tips

Source: Internet
Author: User
Tags array length finally block stack trace throw exception try catch

Front.

Error handling is critical for Web application development, not anticipating possible errors in advance, not taking a recovery strategy in advance, and potentially leading to a poor user experience. Because any JavaScript error can cause a Web page to become unusable, as a developer, you must know when it can go wrong, why it goes wrong, and what is amiss. This article will describe in detail the error handling mechanism in JavaScript

Error Object 

An Error object is an object that contains an error message and is the native object of JavaScript. When the code parsing or run-time error occurs, the JavaScript engine automatically generates and throws an instance of an Error object, and the entire program is interrupted where the error occurred

Console.log (t);//uncaught referenceerror:t is not defined

ECMA-262 stipulates that the Error object includes two attributes: Message and name. The message property holds error messages, and the Name property saves the error type

In general, use the Try-catch statement to catch the error
try{
  t;
} catch (ex) {
  console.log (ex.message);//t is not defined 
  console.log (ex.name);//referenceerror
}

The browser also extends the properties of the Error object, adding other relevant information. The most common browser vendors implement the Stack property, which represents stack trace information (Safari does not support)

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 the wrong object. If the message parameter is specified, the Error object is used as its message property, and if not specified, it uses a predefined default string as the value of the property

New Error ();
New Error (message);  
Generally, use the throw statement to throw the error
throw new error (' Test ');
Uncaught error:test
throw 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 the error () constructor is invoked directly as a function without using the new operator, its behavior is the same as when it is invoked with the new operator

Error ();
Error (message);  

Throw error (' Test ');//uncaught error:test
throw error ();//uncaught error

The Error object has a ToString () method that returns the message property of the ' ERROR: ' + Error Object

var test = new Error (' Testerror ');
Console.log (Test.tostring ());//' Error:testerror '

Error type 

There are several types of errors that may occur during code execution. Each error has a corresponding type of error, and when the error occurs, the appropriate type of error object is thrown. ECMA-262 defines the following 7 types of errors:

Error
Evalerror (eval error)
Rangeerror (range error)
Referenceerror (reference error)
SyntaxError (syntax error)
TypeError ( Type error)
Urierror (URI error)

Where error is the base type and other error types inherit from that type. Therefore, all error types share a set of identical properties. Error type errors are rarely seen if they are also thrown by browsers; The primary purpose of this base type is for developers to throw custom errors

"Evalerror (eval error)"

When the Eval function is not executed correctly, a Evalerror error is thrown. The error type is no longer present in the ES5, but is persisted only to ensure compatibility with the previous code

"Rangeerror (range error)"

Errors of type Rangeerror trigger when a value is out of range, including the range beyond the array length and the number of values beyond the range.

New Array ( -1);//uncaught rangeerror:invalid array length
new array (number.max_value);//uncaught rangeerror: Invalid array length

(1234). toexponential;//uncaught rangeerror:toexponential () argument must be between 0 and 2 0
(1234). toexponential ( -1);////uncaught rangeerror:toexponential () argument must be between 0 and 20

"Referenceerror (reference error)"

Referenceerror (reference error) is triggered when referencing a nonexistent variable or a left value (lvalue) type error

A;//uncaught referenceerror:a is isn't defined 1++;//uncaught referenceerror:invalid left-hand side expression in
post Fix operation

"SyntaxError (syntax error)"

SyntaxError (syntax error) is thrown when the grammar rules are not met

Variable name error
var 1a;//uncaught syntaxerror:unexpected number

//missing bracket
console.log ' hello ');//uncaught syntaxerror:unexpected string

"TypeError (type Error)"

A TypeError type error occurs when an unexpected type is saved in a variable, or when a method that does not exist is accessed. The cause of the error is varied, but ultimately it is because the type of the variable does not conform to the requirements when performing a particular type of operation

var o = new 10;//uncaught typeerror:10 is isn't a constructor
alert (' name ' in true);//uncaught typeerror:cannot use ' I N ' operator to search for ' name ' in true
Function.prototype.toString.call (' name ');//uncaught TypeError: Function.prototype.toString is not generic

"Urierror (URI error)"

Urierror is an error that is thrown when the parameter of the URI-dependent function is incorrect, mainly involving encodeURI (), decodeURI (), encodeURIComponent (), decodeURIComponent (), Escape () and unescape () these six functions

decodeURI ('%2 ');//Urierror:uri Malformed

Error Event

Any error that is not handled by Try-catch triggers the Error event of the Window object

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

To specify onerror event handlers, you can use DOM0-level techniques, or you can use the standard format for 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 return value of the onerror. If the return value is False, an error message is displayed in the console, and if the return value is true, it is not displayed

The console displays error messages
Window.onerror = function (message,url,line) {
  alert (message);
  return false;
}
A;

The console does not display error messages
Window.onerror = function (message,url,line) {
  alert (message);
  return true;
}
A

This event handler is the last line of defense to avoid the browser reporting errors. Ideally, you should not use it whenever possible. As long as you can properly use the Try-catch statement, there will be no error to the browser, and will not trigger the error event

The image also supports the error event. An error event is triggered whenever the URL in the src attribute of the image does not return an image format that can be recognized. The error event in this case follows the DOM format and returns an image-targeted event object

An alert box is displayed when the image is loaded failed. An error event occurs, the image download process has ended, that is, can not be downloaded again

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

Throw statement and throw error 

The throw statement is used to throw an error. When you throw an error, you must specify a value for the throw statement, what type of value it is, no requirement

[note] The process of throwing an error is blocked and subsequent code will not execute

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 ');
throw new Referenceerror (' You didn\ ' t cite your references ');

The prototype chain can also be used to create custom error types by inheriting errors (the prototype chain is described in chapter 6th). At this point, you need to specify the name and message properties for the newly created error type

Browsers treat custom error types that inherit from error, just as they do with other types of errors. It is useful to create a custom error if you want to catch your own thrown error and treat it differently from a browser error

function customerror (message) {
  this.name = ' customerror ';
  this.message = message;
}
Customerror.prototype = new Error ();
throw new Customerror (' My message ');

When the throw statement is encountered, the code stops executing immediately. The code continues to execute only if a Try-catch statement captures the value being thrown

A more detailed explanation is that when an exception is thrown, the JavaScript interpreter immediately stops the currently executing logic and jumps to the nearest exception handler. The exception handler 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 closed code block at a higher level to see if it has an associated exception handler. And so on until an exception handler is found. If the function that throws the exception does not have a Try-catch statement to handle it, the exception propagates up to the code that called the function. In this case, the exception propagates up the lexical structure of the JavaScript method and the call stack. If no exception handlers are found, JavaScript treats the exception as a program error and reports it to the user

Try catch statements and catch errors 

The 3rd edition of ECMA-262 introduced the Try-catch statement as a standard way to handle exceptions in JavaScript to catch and handle errors

Where the TRY clause defines the code block in which the exception is to be handled. After the catch clause follows the TRY clause, the code logic within the catch is invoked when an exception occurs somewhere inside the try block. The catch clause follows the finally block, where the cleanup code is placed, and the logic in the finally block is always executed, regardless of whether an exception is generated in the try block. Although catch and finally are optional, a try clause requires at least one of the two to form a complete statement

try/catch/finally statement blocks need to be enclosed in curly braces, where curly braces are required, even if only one statement in a clause cannot omit curly braces

try{
  //Usually, the code here will start from the beginning without any problems
  //But sometimes throws an exception, either by the throw statement directly or by invoking a method to throw
}catch (e) {
  // If and only if the try statement block throws an exception, the code here is executed
  //Here you can get a reference to the Error object or other values that you throw through the local variable E.
  the code block here can handle this exception for some reason, or ignore the exception. You can also throw the exception
}finally{
  //Regardless of whether the try statement throws an exception, the finally logic always executes, terminating the TRY statement block in the following ways:
  //1, normal termination, The last statement of the statement block is executed
  /2, terminated by a break, continue, or return statement
  //3, throws an exception, the exception is caught by a catch clause/
  /4, throws an exception, the exception is not captured, continues to propagate upward
}

In general, put all the code that might throw the error in a try statement block, and place the code for the error handling in the CATCH block

If any code in the try block has an error, it exits the code execution immediately and then executes the catch block. At this point, the catch block receives an object that has an error message, and the actual information contained in the object will vary by browser, but in common there is a message property that holds the error messages

[note] Be sure to give the Error object a name, empty will report syntax errors

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 that represents the value thrown by the try code block

function Throwit (Exception) {
 try {
  throw exception;
 } catch (e) {
  console.log (' caught: ' + E);
 }
}

Throwit (3);//Caught:3
throwit (' hello ');//Caught:hello
Throwit (new error (' An error happened ')); Caught:Error:An Error happened

Catch code block catch error, program will not be interrupted, will continue to follow the normal process of execution

try{
 Throw "error"; "
catch (E) {
 console.log";
}
Console.log (222);
A
//222

In order to catch different types of errors, the catch code block can be added to the judgment statement

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, the finally clause is used, and its code executes anyway. In other words, the code in the TRY statement block executes normally, the finally clause executes, and the finally clause executes if a catch statement block is executed because of an error. Whenever the code contains a finally clause, no matter what code is contained in a try or catch statement block--even the return statement--does not block the execution of the finally clause

The error is not captured because there are no catch statement blocks. After executing the finally code block, the program interrupts the local
function Cleansup () {
 try {
  throw new error (' Error ... ')
  in the error throw. Console.log (' This row will not execute ');
 } finally {
  Console.log (' Complete cleanup work ');
 }
Cleansup ();
Complete cleanup
//error: Error ...
function testfinnally () {
  try{return
    2;
  } catch (Error) {return
    1;
  } finally{return
    0;
  }
Testfinnally ();//0

[Note that the value of the count for the]return statement is obtained before the finally code block runs, and gets the complete

var count = 0;
function Countup () {
 try {return
  count;}
 finally {
  count++;
 }
} Countup ()///0
Console.log (count);//1
function f () {
 try {
  console.log (0);
  Throw "Bugs";
 } catch (e) {
  console.log (1);
  return true; This sentence would have been delayed until finally code block to execute
  console.log (2);///Will not run
 } finally {
  console.log (3);
  return false; This sentence will cover the previous sentence return
  Console.log (4);///Will not run
 }
 console.log (5);//Will not run
} var result
= f ();
0
//1
//3

Console.log (result);//False

"Tips" block-level scopes

A common use of try-catch statements is to create block-level scopes in which variables declared are valid only within a catch

ES6 introduces the Let keyword and creates block-level scopes for the variables it declares. However, in the case of current ES3 and ES5, try-catch statements are often used to achieve similar effects

The following code shows that e exists only within the catch clause and throws an error when trying to reference it elsewhere

try{
  throw new error ()//Throw errors
}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 is going to happen in your code. Because JavaScript is loosely typed and does not validate parameters of functions, errors only appear during code. In general, you need to focus on three types of errors: type conversion errors, data type errors, communication errors

"Type conversion Error"

A type conversion error occurs when using an operator, or by using a language structure of another data type that may automatically convert a value

A flow control statement is the place where type conversion errors occur easily. Statements such as if are automatically converted to a Boolean value before the next action is determined. Especially if statements, if used incorrectly, the most error-prone

Unused named variables are automatically assigned undefined values. The undefined value can be converted to a Boolean value of false, so the IF statement in the following function only applies to situations that provide a third parameter. The problem is that not only undefined is converted to false, it is not only string values that can be converted to true. For example, if the third argument is a value of 0, then the test for the IF statement fails, and the test for number 1 passes

function Concat (STR1,STR2,STR3) {
  var result = str1 + str2;
  if (STR3) {//never do so result
    + = STR3;
  }
  return result;
}

The use of non-Boolean values in flow control statements is an extremely common source of error. To avoid such errors, it is necessary to actually pass the Boolean value when the condition is compared. In fact, performing some form of comparison can achieve this goal

function Concat (STR1,STR2,STR3) {
  var result = str1 + str2;
  if (typeof Str3 = = ' string ') {//More appropriate result
    = STR3;
  }
  return result;
}

"Data type Error"

JavaScript is loosely typed and does not compare them to ensure that their data types are correct before using variables and function parameters. To ensure that no data type errors occur, only the appropriate data type instrumentation code can be written. Data type errors are most likely to occur when the expected value is passed to the drawing function

Unsafe functions, any non-array value will cause error
function Reversesort (values) {if (values) {
    values.sort ();
    Values.reverse ();
  }

Another common mistake is to compare a parameter to a null value. Comparisons with NULL only ensure that the corresponding values are not null and undefined. To ensure that the value passed in is valid, it is not sufficient to detect only null values

Unsafe functions, any non-array value will cause error
function Reversesort (values) {
  if (values!= null) {
    values.sort ();
    Values.reverse ();
  }

Passing in an object (instead of an array) that contains the sort () method can be detected, but an error may occur when calling the reverse () function

Unsafe functions, any non-array value will cause error
function Reversesort (values) {
  if (typeof values.sort = = ' function ') {
    Values.sort ();
    Values.reverse ();
  }

When you know exactly what type you should pass in, it's best to use instanceof to detect its data type

Safe, non-array values are ignored
function Reversesort (values) {
  if (values instanceof Array) {
    values.sort ();
    Values.reverse ();
  }

"Communication Error"

With the advent of Ajax programming, it has become commonplace for Web applications to dynamically load information or functionality within their lifecycle. However, any communication between JavaScript and the server is likely to produce an error

The most common problem is that the data is not encoded using encodeuricomponent () until the data is sent to the server

Error
Http://www.yourdomain.com/?redir=http://www.sometherdomain.com?a=b&c=d
//For ' redir= ' All subsequent strings call encodeURIComponent () to resolve this problem
http://www.yourdomain.com/?redir=http:%3A%2F% 2fwww.sometherdomain.com%3fa%3db%26c%3dd

The above comprehensive understanding of JavaScript in the error handling mechanism is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.