Throwing strings instead of Errors

Viewed 39574

Since we can throw anything with the throw keyword in Javascript, can't we just throw an error message string directly?

Does anyone know any catch in this?

Let me add some background to this: Very often, in the JavaScript world, people rely on parameter checking as opposed to using the try-catch mechanism, so it makes sense to only throw fatal errors with throw. Still, to be able to catch some system Errors, I have to use a different class for my own errors and instead of creating a subclass of Error, I think I should just use String.

5 Answers

Although you can throw any type of data that you’d like, this is not optimal when debugging. A JS Error object contains all kind of information regarding the Error and a message. Whereas a string can only contain a message.

This additional information includes:

  1. fileName: from which file the error was thrown
  2. Linenumber: from which line the error was thrown
  3. stacktrace: from which function the error was called

Here is for example a stacktrace from chrome devtools:

enter image description here

Related