我正在閱讀Eloquent JavaScript的第8章「Bugs and Error Handling」。我遇到了一個關於錯誤代碼的例子,但我仍然無法理解作者給出的導致失敗原因的所有解釋。讓我們給的背景:在節「Selective Catching」上撰文說:有人能澄清我這個try-catch塊(未定義變量)有什麼問題嗎? (選擇性捕捉,JS)
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.
我想我沒有得到解釋,因爲Enlgish是不是我的母語。我沒有得到的是大膽的句子。我不明白爲什麼catch塊會忽略變量e以及關於錯誤輸入的信息。 catch catch是否認爲e是一個糟糕的輸入?
請問有人可以澄清一下。提前致謝。
我*認爲*解釋假設函數'promptDirection()'將顯式地拋出異常,如果輸入的輸入無效。因此,從'try'塊引發的異常可能是輸入無效,或者來自意想不到的事情 - 比如函數名稱中的拼寫錯誤。 'catch'塊不檢查異常('e'),所以它的行爲就好像用戶輸入了錯誤的東西,即使用戶實際上沒有機會輸入。 – Pointy
感謝隊友,現在好多了! –