1

I have this sample code:

class Person {
  #name = "Jack";
  static hasTitle(obj) {
    try {
      console.log(obj.#age);
    } catch (error) {
      console.log(Object.keys(error));
    }

    return #name in obj;
  }
}

const p = new Person();
console.log(Person.hasTitle(p));

And I want to catch the error that occurs because age is not defined on the Person object. What happens now is that the catch block is never reached, despite wrapping the faulty line with a try/catch block. So what is the problem here?

I'm perfectly aware of the in operator in case you're wondering.

Omar Dulaimi
  • 846
  • 10
  • 30
  • 2
    Since it's a syntax error and not a runtime error, the try-catch block won't catch the issue. You could potentially use `window.onerror`, but really the developer writing the code should fix the issue when it occurs – Nick Parsons Jun 12 '22 at 11:06
  • @NickParsons What about running the code in a node env? Is there a similar function for that? – Omar Dulaimi Jun 12 '22 at 11:09
  • The docs here say that syntax errors can be caught though https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError – Omar Dulaimi Jun 12 '22 at 11:10
  • 1
    That's because those snippets of code "generate" the syntax error at run time, eg, when trying to parse some JSON, calling eval, etc. But that doesn't occur in your case as you're not parsing this code at runtime. – Nick Parsons Jun 12 '22 at 11:18
  • 1
    Not too sure about nodejs, I would imagine that there would be something similar, but nothing that I can think of off the top of my head. – Nick Parsons Jun 12 '22 at 11:18

0 Answers0