错误的类型
ReferenceError
引用的变量不存在
console.log(a); //Uncaught ReferenceError: a is not defined
console.log('此行不会被执行');
TypeError
数据类型不正确
var a = null;
console.log(a.xxx); //Uncaught TypeError: Cannot read property 'xxx' of null
RangeError
数据值不在其所允许的范围内
function fn() {
fn();
}
fn(); //Uncaught RangeError: Maximum call stack size exceeded
SyntaxError
语法错误
var b = """" //Uncaught SyntaxError: Unexpected string
错误处理
捕获错误:
try {
console.log(a);
}
catch (error) {
console.log('出错了:',error.message);
}
`console.log('此行会被执行');
`
抛出错误:
function handleError() {
if(Date.now()%2===0){
throw new Error('异常:当前时间为偶数')
}else{
console.log('正常');
}
}
handleError();
抛出错误并捕获 {#pao_chu_cuo_wu_bing_bu_huo}
function handleError() {
if(Date.now()%2===0){
throw new Error('异常:当前时间为偶数')
}else{
console.log('正常');
}
}
`try {
handleError();
} catch (error){
alert('处理业务出错:' + error.message);
}
`