Error detection (1) ------ try-catch sentence From "Elevation 3"

0 Introduction

Currently read "Elevation 3" error detection section, now dig a pit on the error detection should write three summary: firebug error detection and output information; try-catch error trapping; common type of error.

Benpian logical ideas are as follows: First try-catch statement carried introduce error trapping; then describes common types of errors, which will be combined with firebug to illustrate the point; Secondly try-catch statement and error type combination to catch errors; however, if captured the error to the browser's language representation, or hard to find the error, it is recommended to use throw throw developer-defined error, so that the location and cause of the error will be easier to find; and finally throws and error trapping errors were Summarizing the discussion.

1 try-catch Profile

Good error handling mechanism that allows users and developers to timely reminder, knowing that in the end what happened, so do not panic. ECMA-262 3rd edition introduced try-catch statement, as JavaScript in a standard way to handle exceptions. The basic syntax is as follows,

try{
// 可能会导致错误的代码
} catch(error){
// 在错误发生时怎么处理
}

We should put all might throw error code is placed in the try block, and put that code for error handling in the catch block. If any code in the try block error occurs, it will immediately exit code execution, and then execute the catch block. At this time, catch a block containing the object will receive an error message. Even if you do not want to use the error object, but also specify a parameter name. This object contains the actual information will vary depending on the browser, but there is a common error message that holds the message properties. The message attribute is the only one able to guarantee that all browsers support the property, in addition, IE, Firefox, Safari, Chrome and Opera have added other relevant information for the wrong object. When cross-browser programming, it is best to use only message property.
A test case:
image description

As long as the code is included in the finally clause, regardless try or catch block what is included in the code - even return statement will not prevent the execution of the finally clause. As shown in the following example:

function testFinally() {
  try {
    return 2;
  } catch (error) {
    return 1;
  } finally {
    return 0;
  }
}
function testWithoutFinally() {
  try {
    return 2;
  } catch (error) {
    return 1;
  }
}
console.log(testFinally());//输出0
console.log(testWithoutFinally());//输出2

If the finally clause is provided, the catch clauses became optional (there is a catch or finally can). IE7 and earlier versions have a bug: unless there is a catch clause, or finally code is never executed. IE8 fixes this bug. If you still want to consider an earlier version of IE, it had to provide a catch clause, even if there is not anything to write.

Another test case:

var example = function() {
  try {
    window.someNonexistentFunction();
  } catch (error) {
    console.log(error.name);
    console.log(error.message);
    return 1;
  } finally {
    console.log('everything is over');
  }
};
example();

Test results: Has the implementation of the try / catch / finally statements, the question is why would the return statement in the final implementation of a catch? It is a problem for themselves.
image description

Error type 2

Each has a corresponding error type of the error, and when an error occurs, the error will be thrown corresponding object type (error object). ECMA-262 defines the following seven kinds of error types:

1) Error is a base type, other error types are inherited from the type. Therefore, all error types share the same set of attributes (for error object all default object method).
When thrown 2) EvalError type of error exception occurs when you use eval () function, but not necessarily EvalError thrown error type. Without the eval () as a function call, Firefox 4+ IE8 and this throws TypeError.

3) RangeError types of errors will be triggered when the value exceeds the corresponding range. For example, when defining the array, if the number of items in the array are not supported (such as -20 or Number.MAX_VALUE) is specified, it will trigger this error.

4) In the case of an object can not be found, ReferenceError occurs (in this case, will directly lead to well-known "object expected" browser error). Normally, when accessing a variable that does not exist, this error occurs.

5) As for SyntaxError, when we passed a syntax error in JavaScript string eval () function, it will lead to such errors. If a syntax error code appears outside the eval () function is less likely to use SyntaxError, because the syntax error causes the JavaScript code to immediately stop the execution.

6) When TypeError type often used in JavaScript, preserved in a variable type of accident, or when the access method that does not exist, this will lead to error. Although the cause of the error varied, but the final analysis, or because when performing specific types of operations, types of variables does not meet the requirements due. Wrong type of situation occurs most often, is the parameters passed to the function without prior examination, the results of the incoming type does not match the expected type.

7) When using encodeURI () or decodeURI (), and URI format is incorrect, it will lead URIError error. This error is also very rare, because the fault tolerance said earlier, these two functions are very high.

FF in the above test procedure are as follows:

image description

3 Use the try-catch statement to catch errors

To know the type of error, it can be used in instanceof operator catch statement in the try-catch statement as follows.

try {
  someFunction();
} catch (error){
  if (error instanceof TypeError){
//处理类型错误
} else if (error instanceof ReferenceError){
//处理引用错误
} else {
//处理其他类型的错误
}
}

In cross-browser programming, check for errors is the easiest way to determine the type of treatment; and error messages included in the message attributes will vary depending on the browser.
Use try-catch best suited to deal with those mistakes that we can not control. Suppose you use a large function JavaScript library, intentionally or unintentionally, the function may throw some errors. Since we can not modify the source code for the library, it can be placed in the large call the function try-catch statement which, if there are any errors, beating properly handle them.

4 throw throws a custom error

And try-catch statement to match the operator as well as a throw, throw a custom error for any time. When an error is thrown, you must give the throw operator to specify a value, this value is what type, there is no requirement. Throw in the face of the operator, the code will immediately stop the execution. Only when there is try-catch statement to capture the value to be thrown, the code will continue.

By using a custom built-in error types, can more realistically simulate browser error. Each error type constructor takes one argument, i.e., the actual error message. Here is an example.

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 browser will be like handling errors generated by itself, as the code to handle errors thrown. In other words, the browser will report the error in a conventional manner, and will appear here custom error messages.

Throws a custom error meaning: easily and quickly locate the error and error correction. Although the browser on their own error, but the error message can not reach unity in the browser, and if the same type of error occurs, look for the source is complex, especially in the thousands of lines of code. But if you know the possible error codes can be added directly from your code these custom errors, once these errors, browser errors reported by the definition, the key is the wrong location and type of obvious.
Example: the array must receive a parameter of the function as an argument will be given if the received character string.

function process(values){
    values.sort();
    for (var i=0, len=values.length; i < len; i++){
        if (values[i] > 100){
            return values[i];
        }
    }
    return -1;
}
var a = process("string");
 console.log(a);

firebug result: Adding Custom error codes:
image description

function process(values){
  if (!(values instanceof Array)){
    throw new Error("process(): Argument must be an array.");
  }
    values.sort();
    for (var i=0, len=values.length; i < len; i++){
        if (values[i] > 100){
            return values[i];
        }
    }
    return -1;
    }

var a = process("string");
 console.log(a);

firebug result:
image description

If the values ​​argument is not an array, it will throw an error. The error message includes the name of the function, and why a clear description of the error will occur. If this error a complex Web application occurs, then look for the root of the problem would be easier.

You can also use the prototype chain to create custom error types by inheritance Error. At this point, you need to specify the name and the type of error message attribute is newly created.
One example:

//通过继承Error实现自定义错误类型,要定义name和message属性
   function CustomError(message){       
       this.name = "CustomError";
       this.message = message;
   }
   CustomError.prototype = new Error();

   function process(values){
       //如果出现错误,就抛出自定义错误类型的对象实例
       if (!(values instanceof Array)){
           throw new CustomError("process(): Argument must be an array.");
       }
       values.sort();
       for (var i=0, len=values.length; i < len; i++){
           if (values[i] > 100){
               return values[i];
           }
       }
       return -1;
   }

   process("string");

firebug display custom types of errors:

image description

5 throw an error using the try-catch catch errors

About when to throw an error, and when to use try-catch to catch them, is a commonplace problem. In general, low-level application architecture often will throw an error, but this level does not affect the current implementation of the code, so errors are usually not the real deal. If you intend to write a JavaScript library to be used in many applications, only one could even write the auxiliary function in multiple locations inside the application, I strongly recommend that you provide detailed information when an error is thrown. Then, you can capture in your application and properly handle these errors.
When it comes to throw errors and capture errors, we should think only capture those you know exactly how to deal with errors. The purpose is to avoid error capture browser by default to deal with them; and throw an error aims to provide information on the specific cause of the error.

Guess you like

Origin www.cnblogs.com/homehtml/p/12594072.html