120

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.

3
  • 3
    While it's possible, does it make sense? I'd rather catch an error than a string.
    – Rob W
    Commented Jul 16, 2012 at 9:59
  • 1
  • exports.login = (req, res) => { login(req).then(({ token, user }) => { res.send(token); }).catch(err => { if(typeof err === 'string') { res.status(401).send(err); } else { console.log(err); res.status(500).send('Something went wrong'); } }); } I do handle errors this way, I am also confused, am I doing it right way.
    – Md Adil
    Commented Oct 27, 2017 at 6:56

6 Answers 6

95

While it is okay possible to throw any value, it is generally considered poor form to throw anything other than an instance of Error or one of its subclasses. There are several reasons for this:

  1. Catching code may expect the thrown object to have the usual message, stacktrace, and name properties that appear on Errors.
  2. Lack of a stacktrace makes debugging problematic, especially in the case of uncaught exceptions / unhandled rejections. E.g. Debugging an "Uncaught [Object object]" error can be particularly painful.
10
  • 12
    For example, it may assume that the .message property of the Error is a string, try to call a string method on it, and explode.
    – Mark Amery
    Commented Feb 14, 2015 at 19:08
  • 8
    You can, but I wouldn't say it's "okay".
    – 1j01
    Commented Oct 22, 2016 at 2:10
  • 9
    This is an awful idea since it means you will have a much harder time debugging the bug without a stack trace. Commented Oct 19, 2017 at 13:37
  • 4
    @BenjaminGruenbaum If you throw a string in Chrome, you do get a stack trace. E.g ` function a() { throw "Hello World"; } a();` will have a stacktrace like this: a @ main.js:4 (anonymous) @ main.js:7
    – doubleOrt
    Commented Oct 26, 2017 at 18:05
  • 1
    @Taurus thanks, I didn't know that - now try doing it with the debugger not connected on in firefox :) Commented Oct 26, 2017 at 18:40
66

Yes, you can throw other values, but it's not a good practice.

Does anyone know any catch in this?

A string is not an error object, and does not convey any useful debugging information. Devtools rely on that, such as the file and line where the error was created, the stacktrace at the throw location etc, which are available as properties on Error objects.

Whenever you think of throwing a primitive string value, throw a new Error("<the string>") instead.

7
  • 14
    It's worth noting that the Chrome devtools will print a stack trace even if you throw a string. You lose the .stack property which can be useful for some automated error handling (e.g. when setting up automated reporting of errors to a server to let you debug things that go wrong in production), but that's more of an edge case; day-to-day manual debugging in-browser works fine if you throw strings.
    – Mark Amery
    Commented Feb 14, 2015 at 19:04
  • 2
    Also note that there is a speed advantage to throwing (and catching) strings instead of errors: jsbench.me/1gkqk6dm06/2 My results: 237k ops/s for errors, 1.168m ops/s for strings. This almost never matters, but theoretically could. (eg. if you use string-throwing simply to "escape" to a higher-level function-call for some reason)
    – Venryx
    Commented Jul 1, 2021 at 0:38
  • @Venryx If you want to use exceptions for control flow, not for errors, I'd recommend not use strings either (although of course I would recommend not to do this at all). throw null;, if you must, or if you need different return codes, use symbols or constant objects.
    – Bergi
    Commented Jul 1, 2021 at 1:39
  • @Bergi Thank you for your comment. However, I extended the perf-test just now, and throw null; appears to only be ~1% faster than throw "some string";: jsbench.me/1gkqk6dm06/3 Perhaps the latest versions of V8 have optimized them to where they're about equivalent?
    – Venryx
    Commented Jul 1, 2021 at 5:35
  • 1
    @Venryx I didn't mean to say that throwing null would be faster, but only that it was cleaner. You just shouldn't throw "Test1" because it's confusing.
    – Bergi
    Commented Jul 1, 2021 at 8:38
25

You can throw errors with messages, you know.

try {
    throw new Error("This is an error");
} catch (e) {
    alert(e.message); // This is an error
}

But you can actually throw strings:

try {
    throw "This is an error";
} catch (e) {
    alert(e); // This is an error
}
2
  • 5
    Sorry for not making the questions clear. I know these all work, but I am interested in the potential problems with using Strings directly as opposed to using an Error object.
    – billc.cn
    Commented Jul 16, 2012 at 12:21
  • Ah, ok, then just have a look to Ianzz's comment. It sums up all the caveats in that. But my advice is still to throw Error objects with custom messages. It saves you the trouble to check for the error type to tell 'your' errors from other natively-generated errors... Unless, of course, you want to do that on purpose (then maybe re-throwing the Error objects in the catch scope).
    – MaxArt
    Commented Jul 16, 2012 at 15:41
5

As others have mentioned above, if you are not throwing an Error object, then you must have try/catch blocks to trap these objects and handle them appropriately or else be in a world of hurt for debugging.

However, when it comes to throwing Errors for non-error handling purposes like controlling program flow, this may be a helpful way to utilize throw without an Error.

When using throws to control program flow, it can be inefficient in any language as the runtime will often do a lot of heavy lifting to unwind call stack information and serialize the data so its available to the user land scope. By avoiding Error creation, you can avoid this performance hit. The key is that you must have a handler up the call stack that knows how to handle this situation. For instance if you throw {isHardStop: true, stopCode: SOME_CODE} and design the handlers to detect this, you may be able to flatten out some of your code or choose cleaner syntax.

Your handler for this ladder case could be structured like:

try { ... } catch(thr) {
    if(!thr){
       // Is not Error or Json - Handle accordingly
    } else if(thr.isHardStop){
       // Handle the stop
    } else {
       // Most likely a real error. Handle accordingly
    }
}
2
  • No, If you need to drive program flow you return/resolve with a value that can handle program flow. An exception is exceptional. If you can not recover and need the system to throw an exception then this is not for program flow but for exception handling.
    – Sukima
    Commented Nov 15, 2018 at 16:15
  • I agree that errors and exceptions should not be thrown for purposes other than exception handling. However, in my example I am just throwing an object and not instantiating an error and thus its just using the try / catch mechanism for an alternative flow control. There should be a negligible performance hit but trainability is not ideal. With that said, have never done this myself and probably wouldn't these days. Instead, I would probably use a method like used in Erlang / Elixir by wrapping the logic in a lambda that returns a success identifier and a result value. Commented Nov 16, 2018 at 17:37
3

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

0

Catch for error message strings like the following:-

try {
    throw new Error("This is an error");
} catch (e) {
    const errorString1 = String(e) // errorString1 = "Error: This is an error"
    const errorString2 = e.message // errorString2 = "This is an error"
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.