我有以下代码:
try {
...
try {
// This is *never* called
alert('TRY');
} catch (e) {
// But this *is* called
alert('CATCH');
}
} catch (e2) {
...
}
问题是,来自内部 catch
block 的警报被执行,但不是来自内部 try
的警报。
这是否完全符合规范,或者有人知道这里发生了什么吗?
可以异常(exception)吗?异步代码运行到另一个 catch block 的上下文中?
注意这是我放在那里的真实代码,内部 try
/catch
没有遗漏!
一些异步代码可能会在进入 block 之前运行。
这是从在 PyQt 4.9.0 和 Qt 4.8.0 的 WebKit/QtWebKit 中运行的网络应用程序中获取的代码。
好的,所以这里是内部 try/catch 之前的更多代码(第一个省略号所在的位置):
DoSomething(function () {
var updatePromises = [];
var p;
for (...) {
p = new Promise();
updatePromises.push(p);
// Run asynchronous code to fulfill promise.
// Calls are chained using an array and a "setTimeout()" mechanism.
tasks.chain(function (promise) { ... }, this, p);
}
(function () {
...
}).future().apply(this, updatePromises);
}.bind(this));
最佳答案
ES5 specification说了以下内容(添加了重点):
The try statement encloses a block of code in which an exceptional condition can occur, such as a runtime error or a throw statement. The catch clause provides the exception-handling code.
...
The production TryStatement :
try
Block Catch is evaluated as follows:
- Let B be the result of evaluating Block.
- If B.type is not throw, return B.
- Return the result of evaluating Catch with parameter B.
我对此的理解是,根据规范,如果不首先评估 try block ,就无法执行 catch block 。
关于JavaScript 捕获上下文错误的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11104126/