错误类型、错误处理、错误对象:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
/*
目标:进一步理解]S中的错误( Error)和错误处理
mdn文档: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Error
1.错误的类型
Error:所有错误的父类型
ReferenceError: 引用的变量不存在
TypeError: 数据类型不正确的错误
RangeError: 数据值不在其所允许的范围内
SyntaxError: 语法错误
2.错误处理
捕获错误:try...catch
抛出错误: throw error
3.错误对象
name属性:错误的类型
message属性:错误相关信息
stack属性:函数调用栈记求信息
*/
// 1.常见的内置错误
//1.1 ReferenceError: 引用的变量不存在
// console.log(a) //ReferenceError: a is not defined
// console.log('---------')//没有捕获error ,下面的代码不会执行
//1.2 TypeError: 数据类型不正确的错误
// let b
// console.log(b.xyz)// TypeError : Cannot read property 'xyz' of undefined
// b={}
// b.xyz() //TypeError: b.xyz is not a function
//1.3 RangeError: 数据值不在其所允许的范围内
// function fn(){
// fn()
// }
// fn()// RangeError: Maximum call stack size exceeded
//1.4 SyntaxError: 语法错误
// const c = """" //SyntaxError: Unexpected string
//2. 错误处理
//捕获错误:try...catch
try {
let b
console.log(b.xyz)
} catch (error) {
console.log(`${error.name}:${error.message}`)
console.log(`${error.stack}`)
}
console.log('注意就算try里面有错误,也不影响try{}catch(){}后面的代码执行')
//抛出错误:throw error
function something() {
if (Date.now() % 2 === 1) {
console.log('当前时间是奇数,程序正确')
} else {
throw new Error('当前时间是偶数,程序错误')
}
}
//捕获抛出的异常
try {
something()
} catch (error) {
console.log(error.message)
}
</script>
</html>
还没有评论,来说两句吧...