1, Error instance object
When parsing JavaScript or run once an error occurs, the engine will throw an error object. JavaScript native in the Error
constructor, all thrown errors are examples of this constructor.
var err = new Error('出错了');
console.log(err.message); // "出错了"
In the above code, we call the Error
constructor to generate an instance object err
. Error
Constructor takes a parameter indicating error, from the instance message
to read the parameter attributes. Throw Error
after instance of an object, the entire program is interrupted where the error occurred, no longer execute down.
JavaScript language standards referred only, Error
instance of an object must have a message
property, which is when the error message, no mention of other attributes. Most JavaScript engine, for Error
instance also provided name
and stack
properties, 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 name
and message
these two attributes, you can have a rough idea of what went wrong.
if (error.name) {
console.log(error.name + ': ' + error.message);
}
stack
Properties 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 throwit
function, then the catchit
function, and finally the operating environment function.
2, the native type of error
Error
Instance 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 Error
a six-derived object.
2.1 SyntaxError objects
SyntaxError
Object 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
ReferenceError
Objects 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 this
assignment.
// 等号左侧不是变量
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.log
operating results and the this
evaluation, the results have led to ReferenceError
an error.
2.3 RangeError objects
RangeError
Objects 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 Number
a method object parameter out of range, and exceeds the maximum stack function.
// 数组长度不得为负数
new Array(-1)
// Uncaught RangeError: Invalid array length
2.4 TypeError objects
TypeError
Objects 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 new
commands, such an error is thrown, as new
parameters 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 TypeError
an error because the obj.unknownMethod
values are undefined
, rather than a function.
2.5 URIError objects
URIError
The 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
eval
When the function is not executed properly, it will throw EvalError
an 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 Error
the object. Then, you can generate a custom of this type of mistake.
new UserError('这是自定义的错误!');
4, throw statement
throw
Statement 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 x
less 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 throw
thrown its argument is wrong, here is an Error
example.
throw
You 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, throw
thrown an UserError
example.
In fact, throw
you 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 throw
statement, the program suspended. Engine will receive throw
information 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...catch
structure 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, try
the code block throws an error (using the example of a throw
sentence), JavaScript engine as soon as the execution of the code, go to the catch
block of code, or the error is the catch block catches. catch
It 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...catch
in 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 catch
block, followed by error processing.
catch
After 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, try
the code block error thrown, by catch
the captured block, the program continues downward.
catch
Among the code block, the error can throw it, or even use a nested try...catch
structure.
var n = 100;
try {
throw n;
} catch (e) {
if (e <= 50) {
// ...
} else {
throw e;
}
}
// Uncaught 100
The above code, catch
in the code threw an error.
In order to capture the different types of errors, catch
among 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, catch
after the capture error, the error type is determined ( EvalError
or RangeError
), different processing is performed.
6, finally block
try...catch
In the final structure allows to add a finally
block 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 catch
statement block, once an error occurs, the code will break execution. Prior to interrupt execution, you will first execute finally
a 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, try
the code block errors have occurred, but which also includes return
the statement, but finally
the code block will still be executed. Moreover, the function's return value or result.
The following example illustrates that return
execution of the statement is ranked finally
before the code, but other finally
codes returned after execution is completed.
var count = 0;
function countUp() {
try {
return count;
} finally {
count++;
}
}
countUp()
// 0
console.log(count);
// 1
Codes described above, return
statements which the count
value is finally
before 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 try
write the file code block, if no error occurs, the operation finally
code block closing the file; once an error occurs, using the first catch
code block error handling, and then close the file using the finally block.
The following examples fully reflect the try...catch...finally
execution 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, catch
before the end of the execution code block, first performs finally
code block.
catch
Among the block of code, triggers into the finally
sign code block, not only return
statements, and throw
statements.
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 catch
following code block, encountered a throw
statement, you will go to execute finally
a block of code, including return false
statements, and therefore directly returned, no longer will go back and perform catch
the rest of the code block.
try
Internal code block can also be re-used try
block.
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, try
there is also a try
. Inner try
error ( console
misspelled), then performs inner finally
code block, then an error is thrown by an outer layer of catch
capture.