3

我有以下代码:

try {
    ...

    try {
        // This is *never* called
        alert('TRY');
    } catch (e) {
        // But this *is* called
        alert('CATCH');
    }

} catch (e2) {
    ...
}

问题是,来自内部catch块的警报被执行,而不是来自内部块的警报try

这是否完全符合规范,或者有人知道这里发生了什么吗?
例如,异步代码的异常可以运行到另一个 catch 块的上下文中吗?

请注意,这是我放在那里的真实代码,内部try/没有遗漏catch!一些异步代码可能会在进入块之前运行。

这是取自在 PyQt 4.9.0 和 Qt 4.8.0 中运行在 WebKit / QtWebKit 中的 Web 应用程序的代码。


好的,所以在内部 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));
4

2 回答 2

1

ES5 规范说明了以下内容(添加了重点):

try 语句包含一个代码块,其中可能发生异常情况,例如运行时错误或 throw 语句。catch 子句提供异常处理代码。

...

产生式 TryStatement : try Block Catch评估如下:

  1. B为评估Block的结果。
  2. 如果B .type 没有抛出,则返回B
  3. 返回使用参数B评估Catch的结果。

我对此的理解是,根据规范,如果不先评估 try 块,就无法执行 catch 块。

于 2012-06-19T15:50:34.237 回答
1

根据Mozilla 参考资料,我认为答案是否定的。我建议您每次进入和退出一个块时都记录一下,看看是否有任何您错过的奇怪事情发生。也许也用。debugger;

或者试试这个:

var foo = false;
try {
    try {
        foo = true;
        throw true;
    } catch (e) {
        if(foo) {
            alert('CATCH');
        } else {
            alert('HUH?');
        }
    }
} catch (e2) {
    alert('CATCH2');
}
于 2012-06-19T15:38:48.137 回答