我们在键盘上留下的余温, 也将随时代传递到更远的将来


:D 获取中...

当代码运行时的发生错误, 会创建新的 Error 对象, 并将其抛出.

Error 的类型

Error: 所有错误的父类型

当像函数一样使用 Error 时, 如果没有 new , 它将返回一个 Error 对象. 所以, 仅仅调用 Error 产生的结果与通过 new 关键字构造 Error 对象生成的结果相同.

1
2
3
// this:
const x = Error('I was created using a function call!');​​​​ // has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');

ReferenceError: 引用的变量不存在

1
console.log(a) // ReferenceError: a is not defined

TypeError: 数据类型不正确的错误

1
2
let b
console.log(b.xxx) // TypeError: Cannot read property 'xxx' of undefined
1
2
let b = {}
b.xxx() // TypeError: b.xxx is not a function

RangeError: 数据值不在其所允许的范围内

1
2
3
4
5
function fun () {
fun()
}

fun() // RangeError: Maximum call stack size exceeded

SyntaxError: 语法错误

1
let c = '''' // SyntaxError: Unexpected string

Error 的处理

捕获错误: try…catch

1
2
3
4
5
try {
console.log(a)
} catch(err) {
console.log(err) // ReferenceError: a is not defined
}

抛出错误: throw Error

1
throw new Error('哎呀, 出错啦!!!')

Error 属性

message: 错误相关信息

1
2
3
4
5
try {
console.log(a)
} catch(err) {
console.log(err.message) // a is not defined
}

stack: 函数调用栈记录信息

1
2
3
4
5
try {
console.log(a)
} catch(err) {
console.log(err.stack) // ReferenceError: a is not defined at <anonymous>:2:15
}

 评论

 无法加载Disqus评论系统,请确保您的网络能够正常访问。