Search code examples
javascriptexceptionthrow

What type of exception should be thrown in JavaScript?


What type of object should be thrown in JavaScript?

I see a lot of examples which throw a plain old string and there seems to be a semi-standard Error type. Should I prefer one over the other?


Solution

  • The Error object and specific error objects such as TypeError are fully standardized in the ECMAScript specification. There are, however, common non-standard properties of these objects available in most browsers.

    You can throw whatever you like, so long as your error handling code knows what to do with the objects you throw, but there are advantages to using Error objects:

    • Consistency with handling errors thrown by native code, such as having a message property, so you don't have to write different code to handle native errors and your own errors;
    • Error objects in Mozilla and other browsers have very useful non-standard properties, such as fileName, lineNumber and stack. You only get these on Error objects and they can be very useful for debugging.