JavaScript 提供了try...catch结构,允许对错误进行处理,选择是否往下执行。
一旦发生错误,程序就中止执行了。对于 JavaScript 引擎来说,遇到throw语句,程序就中止了。引擎会接收到throw抛出的信息,可能是一个错误实例,也可能是其他类型的值。
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
运行try中的代码,如果有错误,就将该错误抛出到catch中处理.
- 如果try和catch模块中不存在return语句,那么运行完try和catch模块中的代码后再运行finally中的代码。
-
如果try和catch模块中存在return语句,那么在运行return之前会运行finally中的代码,
(1). 如果finally中存在return语句,则返回finally的return结果,代码运行结束。
(2). 如果finally不存在return语句,则返回try或catch中的return结果,代码运行结束。 -
如果try和catch模块中存在throw语句,那么在catch运行throw之前会运行finally中的代码。
(1). 如果finally中存在return语句,则返回finally的return结果,代码运行结束。
(2). 如果finally不存在return语句,则运行catch中的throw语句,代码运行结束。
function f() {
try {
throw '出错了!';
} catch(e) {
console.log('捕捉到内部错误');
throw e; // 这句原本会等到finally结束再执行
} finally {
return false; // 直接返回
}
}
try {
f();
} catch(e) {
// 此处不会执行
console.log('caught outer "bogus"');
}
// 捕捉到内部错误