w3schools says that exceptions can be strings, integers, booleans, or objects, but the example given doesn’t strike me as good practice, since exception type checking is done through string comparison. Is this the preferred method of exception handling in JavaScript? Are there built-in exception types (like NullPointerException)? (if so, what are they, what kind of inheritance do they use, and are they preferred over other options?)
w3schools says that exceptions can be strings, integers, booleans, or objects, but the example
Share
Exceptions can be anything you like.
In other languages, exceptions should be instances, and then the
catchstatement chooses which exceptions to catch and which to let fall through by the class of the instance.JavaScript, however, does not have this feature. You can only catch all exceptions, and then look at the value to decide what to do with it. If you don’t want to handle an exception you have to re-throw the caught value manually. (This inevitably makes
catchstatements rather messy.)You can decide to implement your exceptions as objects and compare them with
instanceof. Or you could have unique opaque values to compare against. Or you can even throw straight strings or numbers if you really want to.Kind of. ECMAScript defines some standard error classes:
Errorand its subtypesEvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError. However there are browser implementation issues, for exampletry { nonexistentvar; }givesTypeErrorunder IE instead ofReferenceError. And there are many other browser-specific exceptions particularly when dealing with the DOM.It’s not traditional to use these objects directly, and trying to subclass them is messy (since JavaScript doesn’t have a class system as such). You would tend to stick to your own defined exceptions for your own apps’ use instead. Exceptions are not that widely-used in JavaScript.