javascript - javascript HTML W/R/T Later 函数中如何处理未定义的错误

标签 javascript

我遇到了一个我以前没有考虑过的问题。如果我有一个在每个页面上运行的 main.js 脚本,但我的一个或多个页面不包含该脚本引用的元素(例如,联系表单不在某个页面上,其中脚本运行)JavaScript 出错后代码会发生什么情况。似乎错误之后的任何代码都不会运行,即使我认为 Javascript 会忽略这些错误。例如: 如果我有以下代码

var el = document.querySelector('#el'); //Not a real element
el.addEventListener('click', function () {
    console.log('Here');
}, false);

//The console errors "can not add eventListener of null"

alert('Test'); //This will never execute?

最后一行永远不会执行吗?

最佳答案

来自specification :

If an algorithm is defined to “throw an exception”, execution of the algorithm is terminated and no result is returned. The calling algorithms are also terminated, until an algorithm step is reached that explicitly deals with the exception, using terminology such as “If an exception was thrown…”. Once such an algorithm step has been encountered the exception is no longer considered to have occurred.

尽管这主要解决规范中定义的算法,但由于程序的执行也在规范中定义,因此它也适用于用户域代码的执行。

所以,是的,最后一行不会被执行,因为抛出错误时程序将终止。

关于javascript - javascript HTML W/R/T Later 函数中如何处理未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27790515/

相关文章:

javascript - 关于 JavaScript、WebSockets、WebGL 的问题

javascript - Jquery Loop 无限运行

javascript - 如何从已知子对象 ID 的对象中检索子对象

javascript - $(this) 正在选择窗口对象而不是单击元素 jquery

javascript - 如何使用 Jest 检查对象属性是否匹配?

javascript - HTML - 如何在 OnClick 事件中更改按钮背景颜色

javascript - 高宪章: capture currently selected min and max dates in stock plot

JavaScript 贷款计算器问题

javascript - console.log 多维数组

javascript - 转换后 React Router 滚动页面到顶部