1.try…catch
在try中发生错误,不会执行错误后的try里面的代码,但是会执行catch中的代码
try {
console.log('a');
console.log(b); //错误语句,在try中不报错,继续执行后续代码
console.log('c'); //在错误信息后,不执行
} catch(e) { //error.name error.message
console.log('f'); //catch捕捉到错误,
}
console.log('e');
//输出
// a f e
将catch中改为
try {
console.log('a');
console.log(b);
console.log(c); // 有两处错误,但是第二处错误不会被捕捉到
// 因为上一句错误,这句已经不会被执行
} catch(e) {
console.log(e.name+ ':' + e.message);
}
console.log('e');
//输出 ReferenceError:b is not defined
try…catch就是为了容错,在系统不报错的情况下,让你知道错误信息,且能继续执行后面的代码
2.错误信息
- EvalError:eval()的使用与定义不一致
- RangeError:数值越界
- ReferenceError:非法或不能识别的引用数值
- SyntaxError:发生语法解析错误
- TypeErr