什么是Node.js中未捕获的exception?
什么是在Node.js未捕获的exception(和一般的例外)?
所有的资源都是关于如何处理它们的,但是我还没有find任何解释它们是什么以及为什么会发生的事情。
当代码执行某些事情时,会发生exception。 各种各样的事情有很多types的例外。
例如:
var array = ["A", "B", "C"]; var s = array[1357].toLowerCase(); // TypeError: Cannot read property 'toLowerCase' of undefined someOther.code().toRun(); // this will NOT run, execution is aborted at the exception
这是一个例外。
未被捕获的意思是没有任何代码正在寻找这个可执行的代码,以便它能被优雅地处理。 未捕获的exception停止执行您的代码,并在控制台中显示为错误。 未捕获的exception在生产代码中是非常糟糕的事情。
您使用try / catch块捕获未捕获的exception。 你可能在所有那些你find的“如何处理它们”的资源中读到。
try { var array = ["A", "B", "C"]; var s = array[1357].toLowerCase(); } catch (e) { console.log("Don't do that, seriously"); } someOther.code().toRun(); // this does run, execution continues after caught exception
一个例外是基本上什么时候“打破”。 例如:
alert(x);
会导致“ReferenceError:x未定义”,因为x还没有被定义。 这是一个未被捕获的例外。
处理exception的一种方法是将它们包装在一个简单的try / catch中:
try { alert(x) } catch (e) { alert("x wasn't defined"); }
为了让代码顺利运行,您需要尝试捕获并处理所有潜在的exception,否则脚本将停止处理。
阅读更多关于MDN