javascript try catch not fully working in firefox

ⅰ亾dé卋堺 提交于 2019-12-12 15:25:28

问题


Can someone explain me why this:

<html>
<head></head>
<body>
    <script>
        try {
            document.attribute-withminus = 5;
        }
        catch(e) {
            alert('something went wrong');
        }

        alert('ok');
    </script>
</body>
</html>

Doesn't give me an alert with 'something went wrong' and also no alert with 'ok'?

It works fine in chrome. But in firefox, it just exits (it does show an error in the web console). The whole point of that try-catch is to make sure that if I type something wrong, it should give me an alert saying so. I don't want to have the web console open all the time.

Also, I know what is wrong here (minus sign in attribute; should use setAttribute). I'm asking why my error wasn't caught.


回答1:


document.attribute-withminus = 5;

is a syntax error (probably something like "invalid left hand part in assignement") which is an early error, not a runtime error.

The browser isn't supposed to execute the script containing it, it's supposed to stop and report the error as soon as it compiles the code containing the error, prior to any evaluation. In most browsers, the script would be wholly compiled before reaching the try clause. It works in Chrome because Chrome delays the compilation until it needs the internal block.



来源:https://stackoverflow.com/questions/22037163/javascript-try-catch-not-fully-working-in-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!