silicakes
silicakes

Reputation: 6902

JS try won't catch a thrown error

Looking at the following code:

HTML

<a href="#" id="href" onclick="onClick('it's', 'a', 'new', 'dawn')">foo</a>

JS

function onClick() {

}

try {
  // Uncaught SyntaxError: missing ) after argument list --> 
  // since the quotes don't match under the onclick='.. attribute
  href.onclick;
} catch (e) {
    // no propegation over here
}

I get the aformentioned exception inside the try statement, however, there's no passing into the catch statement.

It happens on both Chrome and FF and I've been wondering why.

Fiddle: https://jsfiddle.net/wqob0x7d/1/

Upvotes: 2

Views: 101

Answers (1)

Pointy
Pointy

Reputation: 413709

You can't catch syntax errors. They're not thrown at runtime — they are detected before the code is run. The parser can't tell what the code is supposed to mean because it doesn't conform to the syntax it expects, so it just throws up its little hands and produces that error.

That said, there are certain times when your code can be in control of errors thrown by the parser:

  • when your code is using eval() or the Function constructor to turn strings into executable code. That implicitly involves the services of the parser, which will behave the same way with erroneous code.
  • when using JSON.parse() to interpret a serialized object. That's a different parser, but you can catch its errors too.

Upvotes: 3

Related Questions