javascript - 有人可以澄清我这个 try-catch block ( undefined variable )有什么问题吗? (选择性捕捉,JS)

标签 javascript exception try-catch

我正在阅读 Bugs and Error Handling 中的第 8 章“Eloquent JavaScript” 。我遇到了一个关于错误代码的例子,但我仍然没有明白作者给出的关于导致失败的原因的解释。让我们给出上下文:在“Selective Catching”部分,作者说:

Invalid uses of the language, such as referencing a nonexistent variable, looking up a property on null, or calling something that’s not a function, will also result in exceptions being raised. Such exceptions can be caught just like your own exceptions.

When a catch body is entered, all we know is that something in our try body caused an exception. But we don’t know what, or which exception it caused.

JavaScript (in a rather glaring omission) doesn’t provide direct support for selectively catching exceptions: either you catch them all or you don’t catch any. This makes it very easy to assume that the exception you get is the one you were thinking about when you wrote the catch block.

But it might not be. Some other assumption might be violated, or you might have introduced a bug somewhere that is causing an exception. Here is an example, which attempts to keep on calling promptDirection until it gets a valid answer:

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

The for (;;) construct is a way to intentionally create a loop that doesn’t terminate on its own. We break out of the loop only when a valid direction is given. 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. Not only does this cause an infinite loop, but it also “buries” the useful error message about the misspelled variable.

我想我没有得到解释,因为英语不是我的母语。我不明白的是大胆的句子。我不明白为什么 catch block 确实忽略变量 e 以及有关错误输入的事情。 catch block 是否假定 e 是错误的输入?

请有人向我解释一下这一点。提前致谢。

最佳答案

作者并不是说 JavaScript 总是忽略 e;他正在谈论这个具体的例子。这个示例代码写得很糟糕(故意):

catch (e) {
    console.log("Not a valid direction. Try again.");
}

我们捕获一个异常(称为e),但我们不会尝试找出异常的种类。我们总是,总是说“不是一个有效的方向。再试一次。”

此代码假设只有一件事可能出错:输入无效。

关于javascript - 有人可以澄清我这个 try-catch block ( undefined variable )有什么问题吗? (选择性捕捉,JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38980308/

相关文章:

java - 是否可以停止finally block 的执行?

java - JPA 2 : How to use Map<String , Employee> 实体之间的 OneToMany 关系

python - 检查文件是否可以用 Python : try or if/else? 读取

javascript - 从用户输入到搜索的动态 URL

javascript - 当图案可拖动时如何调整图像图案的大小?

javascript - `throw new Error` 和 `throw someObject` 和有什么区别?

Java 错误捕获问题

可靠地识别和处理特定情况,例如错误或警告

javascript - "Circular"菜单使用 SVG

javascript - 重定向 JQuery