try代码块的内容抛出错误后,会直接进入catch,执行catch代码块的内容
try {
throw new Error('出错了!');
} catch (e) {
console.log(e.name + ": " + e.message);
console.log(e.stack);
console.log('ojbk');
}
// Error: 出错了!
// at <anonymous>:3:9
// ...
// ojbk
try代码块抛出错误(上例用的是throw语句),JavaScript 引擎就立即把代码的执行,转到catch代码块,或者说错误被catch代码块捕获了。catch接受一个参数,表示try代码块抛出的值。
try...catch结构允许在最后添加一个finally代码块,表示不管是否出现错误,都必需在最后运行的语句。
function idle(x) {
var a;
try {
console.log(x);
return a = 'a';
console.log(1, a);
} finally {
console.log(2, a);
console.log('FINALLY');
console.log(3, a);
}
}
idle('hello')
// hello
// 2 "a"
// FINALLY
// 3 "a"
try...catch...finally 之间的执行顺序
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
下面代码中,进入catch代码块之后,一遇到throw语句,就会去执行finally代码块,其中有return false语句,因此就直接返回了,不再会回去执行catch代码块剩下的部分了。
function f() {
try {
throw '出错了!';
} catch (e) {
console.log('捕捉到内部错误');
throw e; // 这句原本会等到finally结束再执行
} finally {
alert(1); // 此处被执行
return false; // 直接返回
alert(2); // 此处没有被执行
}
}
try {
f();
} catch (e) {
// 此处不会执行
console.log('caught outer "bogus"');
}
// 捕捉到内部错误
嵌套try的错误用法。内层的try报错,这时会执行内层的finally代码块,然后抛出错误,被外层的catch捕获。
try {
try {
console.log('Hello world!'); // 报错
}
finally {
console.log('Finally');
}
console.log('Will I run?');
} catch (error) {
console.error(error.message);
}
// Finally
// console is not defined