JavaScript syntax: error handling mechanism

1, Error instance object

When parsing JavaScript or run once an error occurs, the engine will throw an error object. JavaScript native in the Errorconstructor, all thrown errors are examples of this constructor.

var err = new Error('出错了');
console.log(err.message); // "出错了"

In the above code, we call the Errorconstructor to generate an instance object err. ErrorConstructor takes a parameter indicating error, from the instance messageto read the parameter attributes. Throw Errorafter instance of an object, the entire program is interrupted where the error occurred, no longer execute down.

JavaScript language standards referred only, Errorinstance of an object must have a messageproperty, which is when the error message, no mention of other attributes. Most JavaScript engine, for Errorinstance also provided nameand stackproperties, respectively, the wrong name and the wrong stack, but they are non-standard, each implementation has not.

  • message: Error message
  • name: Error name (nonstandard properties)
  • stack: Error Stack (non-standard attributes)

Use nameand messagethese two attributes, you can have a rough idea of what went wrong.

if (error.name) {
  console.log(error.name + ': ' + error.message);
}

stackProperties to view the stack when an error occurs.

function throwit() {
  throw new Error('');
}

function catchit() {
  try {
    throwit();
  } catch(e) {
    console.log(e.stack); // print stack trace
  }
}

catchit()
// Error
//    at throwit (~/examples/throwcatch.js:9:11)
//    at catchit (~/examples/throwcatch.js:3:9)
//    at repl:1:5

The above code, the innermost layer of the stack is the error throwitfunction, then the catchitfunction, and finally the operating environment function.

2, the native type of error

ErrorInstance of an object is the most general type of error in its basis, JavaScript also defines six other error object. In other words, there is Errora six-derived object.

2.1 SyntaxError objects

SyntaxErrorObject is a syntax error occurs when parsing code.

// 变量名错误
var 1a;
// Uncaught SyntaxError: Invalid or unexpected token

// 缺少括号
console.log 'hello');
// Uncaught SyntaxError: Unexpected string

Error code above, you can find all the parsing stage, it will be thrown out SyntaxError. The first error is the "token illegal" and the second is the error message "string does not meet the requirements."

2.2 ReferenceError objects

ReferenceErrorObjects are errors that occur when a reference variable does not exist.

// 使用一个不存在的变量
unknownVariable
// Uncaught ReferenceError: unknownVariable is not defined

Another scenario is triggered, a value assigned to the object can not be assigned, such as a function of the operating results or thisassignment.

// 等号左侧不是变量
console.log() = 1
// Uncaught ReferenceError: Invalid left-hand side in assignment

// this 对象不能手动赋值
this = 1
// ReferenceError: Invalid left-hand side in assignment

The above code function console.logoperating results and the thisevaluation, the results have led to ReferenceErroran error.

2.3 RangeError objects

RangeErrorObjects are errors that occur when a value out of range. There are several cases, the length of the array is negative one, the second is Numbera method object parameter out of range, and exceeds the maximum stack function.

// 数组长度不得为负数
new Array(-1)
// Uncaught RangeError: Invalid array length

2.4 TypeError objects

TypeErrorObjects are errors that occur when a variable or parameter is not the expected type. For example, using the values of the original type of string, boolean, numeric and other newcommands, such an error is thrown, as newparameters of the command should be a constructor.

new 123
// Uncaught TypeError: number is not a func

var obj = {};
obj.unknownMethod()
// Uncaught TypeError: obj.unknownMethod is not a function

The second case above code, the method call object does not exist, will throw TypeErroran error because the obj.unknownMethodvalues are undefined, rather than a function.

2.5 URIError objects

URIErrorThe object is to throw the URI parameter of the correlation function is not correct errors, mainly related to encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(), escape()和unescape()six function.

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

2.6 EvalError objects

evalWhen the function is not executed properly, it will throw EvalErroran error. This type of error is no longer used, but in order to ensure compatibility with the code before, only to be maintained.

2.7 summary

The six errors derived above, along with the original Error object are constructors. Developers can use them manually generate error object instance. These constructors accept a parameter representative of the error message (message).

var err1 = new Error('出错了!');
var err2 = new RangeError('出错了,变量超出有效范围!');
var err3 = new TypeError('出错了,变量类型无效!');

err1.message // "出错了!"
err2.message // "出错了,变量超出有效范围!"
err3.message // "出错了,变量类型无效!"

3, custom errors

JavaScript error object addition to the seven original offer, you can also define your own error object.

function UserError(message) {
  this.message = message || '默认信息';
  this.name = 'UserError';
}

UserError.prototype = new Error();
UserError.prototype.constructor = UserError;

The above code is a custom error object UserError, it inherits Errorthe object. Then, you can generate a custom of this type of mistake.

new UserError('这是自定义的错误!');

4, throw statement

throwStatement is used to manually interrupt program execution, throw an error.

if (x <= 0) {
  throw new Error('x 必须为正数');
}
// Uncaught ReferenceError: x is not defined

The above code, if the variable is xless than or equal 0, to manually throw an error, tell the user the value of x is incorrect, the entire program will execute interrupt here. It can be seen throwthrown its argument is wrong, here is an Errorexample.

throwYou can also throw a custom error.

function UserError(message) {
  this.message = message || '默认信息';
  this.name = 'UserError';
}

throw new UserError('出错了!');
// Uncaught UserError {message: "出错了!", name: "UserError"}

The above code, throwthrown an UserErrorexample.

In fact, throwyou can throw any type of value. That is to say, its argument can be any value.

// 抛出一个字符串
throw 'Error!';
// Uncaught Error!

// 抛出一个数值
throw 42;
// Uncaught 42

// 抛出一个布尔值
throw true;
// Uncaught true

// 抛出一个对象
throw {
  toString: function () {
    return 'Error!';
  }
};
// Uncaught {toString: ƒ}

For JavaScript engines, encountered throwstatement, the program suspended. Engine will receive throwinformation thrown example might be a mistake, it could be other types of values.

5, try ... catch structure

Once the error occurs, the program will suspend the execution. JavaScript provides a try...catchstructure that allows for error processing, choose whether to perform down.

try {
  throw new Error('出错了!');
} catch (e) {
  console.log(e.name + ": " + e.message);
  console.log(e.stack);
}
// Error: 出错了!
//   at <anonymous>:3:9
//   ...

The above code, trythe code block throws an error (using the example of a throwsentence), JavaScript engine as soon as the execution of the code, go to the catchblock of code, or the error is the catch block catches. catchIt accepts a parameter value indicating the try block thrown.

If you are not sure whether some of the code error, you can put them try...catchin a block of code, to facilitate further handling errors.

try {
  f();
} catch(e) {
  // 处理错误
}

In the above code, perform the function f if given, will be catchblock, followed by error processing.

catchAfter the code block to catch the error, the program will not be interrupted, it will continue execution in accordance with normal procedures.

try {
  throw "出错了";
} catch (e) {
  console.log(111);
}
console.log(222);
// 111
// 222

In the above code, trythe code block error thrown, by catchthe captured block, the program continues downward.

catchAmong the code block, the error can throw it, or even use a nested try...catchstructure.

var n = 100;

try {
  throw n;
} catch (e) {
  if (e <= 50) {
    // ...
  } else {
    throw e;
  }
}
// Uncaught 100

The above code, catchin the code threw an error.

In order to capture the different types of errors, catchamong the code blocks may be added 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);
  }
  // ...
}

In the above code, catchafter the capture error, the error type is determined ( EvalErroror RangeError), different processing is performed.

6, finally block

try...catchIn the final structure allows to add a finallyblock of code indicating whether or not an error, are required to run in the final statement.

function cleansUp() {
  try {
    throw new Error('出错了……');
    console.log('此行不会执行');
  } finally {
    console.log('完成清理工作');
  }
}

cleansUp()
// 完成清理工作
// Uncaught Error: 出错了……
//    at cleansUp (<anonymous>:3:11)
//    at <anonymous>:10:1

The above code, because there is no catchstatement block, once an error occurs, the code will break execution. Prior to interrupt execution, you will first execute finallya block of code, and then to the user prompts an error message.

function idle(x) {
  try {
    console.log(x);
    return 'result';
  } finally {
    console.log('FINALLY');
  }
}

idle('hello')
// hello
// FINALLY

The above code, trythe code block errors have occurred, but which also includes returnthe statement, but finallythe code block will still be executed. Moreover, the function's return value or result.

The following example illustrates that returnexecution of the statement is ranked finallybefore the code, but other finallycodes returned after execution is completed.

var count = 0;
function countUp() {
  try {
    return count;
  } finally {
    count++;
  }
}

countUp()
// 0
console.log(count);
// 1

Codes described above, returnstatements which the countvalue is finallybefore the code block will run acquired.

The following is a typical usage scenario finally block.

openFile();

try {
  writeFile(Data);
} catch(e) {
  handleError(e);
} finally {
  closeFile();
}

The above code first opens a file, and then trywrite the file code block, if no error occurs, the operation finallycode block closing the file; once an error occurs, using the first catchcode block error handling, and then close the file using the finally block.

The following examples fully reflect the try...catch...finallyexecution order between the three.

function f() {
  try {
    console.log(0);
    throw 'bug';
  } catch(e) {
    console.log(1);
    return true; // 这句原本会延迟到 finally 代码块结束再执行
    console.log(2); // 不会运行
  } finally {
    console.log(3);
    return false; // 这句会覆盖掉前面那句 return
    console.log(4); // 不会运行
  }

  console.log(5); // 不会运行
}

var result = f();
// 0
// 1
// 3

result
// false

In the above code, catchbefore the end of the execution code block, first performs finallycode block.

catchAmong the block of code, triggers into the finallysign code block, not only returnstatements, and throwstatements.

function f() {
  try {
    throw '出错了!';
  } catch(e) {
    console.log('捕捉到内部错误');
    throw e; // 这句原本会等到finally结束再执行
  } finally {
    return false; // 直接返回
  }
}

try {
  f();
} catch(e) {
  // 此处不会执行
  console.log('caught outer "bogus"');
}

//  捕捉到内部错误

The above code, enter the catchfollowing code block, encountered a throwstatement, you will go to execute finallya block of code, including return falsestatements, and therefore directly returned, no longer will go back and perform catchthe rest of the code block.

tryInternal code block can also be re-used tryblock.

try {
  try {
    consle.log('Hello world!'); // 报错
  }
  finally {
    console.log('Finally');
  }
  console.log('Will I run?');
} catch(error) {
  console.error(error.message);
}
// Finally
// consle is not defined

In the above code, trythere is also a try. Inner tryerror ( consolemisspelled), then performs inner finallycode block, then an error is thrown by an outer layer of catchcapture.

Published 104 original articles · won praise 64 · views 90000 +

Guess you like

Origin blog.csdn.net/cuishizun/article/details/104099002