Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the standard practices for throwing JavaScript Exceptions?

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?)

like image 885
T.R. Avatar asked May 13 '10 08:05

T.R.


People also ask

Can you throw exceptions in JavaScript?

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.

How do you throw an exception in a script?

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.


1 Answers

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.

like image 81
bobince Avatar answered Sep 20 '22 09:09

bobince