为什么这个错误会被忽略?

Why will this error be ignored?

我正在阅读 Eloquent JavaScript 并且有一部分代码我不明白。

for (;;) {
    try {
        var dir = promtDirection(" Where ?"); // ← typo !
        console.log(" You chose ", dir);
        break;
    } catch (e) {
        console.log(" Not a valid direction . Try again .");
    }
}  

书上说:

But we misspelled promptDirection , which will result in an “undefined variable” error. Because the catch block completely ignores its exception value ( e ), assuming it knows what the problem is, it wrongly treats the variable error as indicating bad input.

但是如果它是一揽子捕获异常,它不应该只捕获错字打印行产生的错误吗?

But if it is blanket-catching the exceptions, shouldn't it just catch the error generated by the typo

是的。

此时它会声称方向无效,这不是正确的错误。

and terminate?

不,它会进入for循环的下一次迭代(此时它会遇到相同的错误,无限重复)。

代码的问题是 catch 块假设错误与用户输入有关。但事实并非如此,因为真正的错误(作为 e 传递)从未显示,开发人员将被误导搜索它。要成为 "eloquent",您的代码应该使用 e 变量来显示更有用的消息。