gpt4 book ai didi

javascript - 正确使用 javascript 中的异常

转载 作者:行者123 更新时间:2023-11-30 20:53:28 24 4
gpt4 key购买 nike

请详细说明这到底是什么意思:

'As a general rule, don’t blanket-catch exceptions unless it is for the purpose of “routing” them somewhere—for example, over the network to tell another system that our program crashed. And even then, think carefully about how you might be hiding information.' - Eloquent Javascript

最佳答案

假设你的意思是解释here :

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.

As a general rule, don’t blanket-catch exceptions unless it is for the purpose of “routing” them somewhere—for example, over the network to tell another system that our program crashed. And even then, think carefully about how you might be hiding information.

So we want to catch a specific kind of exception. We can do this by checking in the catch block whether the exception we got is the one we are interested in and by rethrowing it otherwise. (...)

我相信作者所说的“一揽子捕获”异常的意思是捕获异常并且根本不验证其内容,相信您 100% 确定它总是某种错误。

示例代码显示了一个“一揽子捕获”,假设它只会在用户提供无效方向时发生,但错误实际上是由代码中的拼写错误引起的。

因为 catch 并没有真正验证错误是否真的是一个无效方向(catch 中没有 if ,它也不会打印 e 的内容),它捕获(被遗忘)了一个不同的错误*,认为这是一个无效的方向 - 最终处理错误原因的异常。


* 错误将是 undefined is not a function 而不是作者指出的 undefined variable

关于javascript - 正确使用 javascript 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47915888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com