user2839747
user2839747

Reputation: 255

javascript try catch not fully working in firefox

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.

Upvotes: 3

Views: 1023

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382130

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.

Upvotes: 4

Related Questions