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?)
Technically you can throw an exception (throw an error). If you use throw together with try and catch , you can control program flow and generate custom error messages.
To declare a function that throws an error, set its return type to never . The never type is used for functions that never return a value, in other words functions that throw an exception or terminate execution of the program.
Exceptions can be anything you like.
In other languages, exceptions should be instances, and then the catch
statement 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 catch
statements 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.
Are there built-in exception types (like NullPointerException)?
Kind of. ECMAScript defines some standard error classes: Error
and its subtypes EvalError
, RangeError
, ReferenceError
, SyntaxError
, TypeError
, URIError
. However there are browser implementation issues, for example try { nonexistentvar; }
gives TypeError
under IE instead of ReferenceError
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With