What is the difference between `throw 'foo'`, `throw Error('foo')`, `throw new Error('foo')`?
Asked Answered
V

1

10

I've seen 3 different ways of throwing an error in JavaScript:

throw 'message';
throw Error('message');
throw new Error('message');

What is the difference between them?

Note: I am aware of similar questions (1,2,3, etc). None of them cover all three cases.

Vector answered 19/9, 2017 at 8:18 Comment(1)
@RobG I answered my own question, so others wouldn't have to read through all of the other answers : )Vector
V
16

throw is an expression which halts the function and generates an exception. Whatever directly follows throw is passed along in the exception. Think of it as a function with syntax sugar, so instead of writing throw('message') you write throw 'message'. throw new Error('message') is just like throw 'message' except an object is being passed along instead of a string literal.

There is no difference between throw Error('message') and throw new Error('message'): many of the core JavaScript objects allow for the creation of a new object without the new constructor and Error happens to be one of them.

That being said, you should always use throw new Error('message'). The Error object contains a stacktrace and other useful debugging information which is lost when you use a string literal. Creating objects using ES6 classes requires the use of new and extending Error via a class is the only way to preserve stacktraces. Creating a custom error class makes error handling much more uniform.

See Also: extremely elaborate illustration.

Vector answered 19/9, 2017 at 8:18 Comment(1)
Allow me to notice that when passing an Error object, you got access to Error.prototype.message attribute in the object. It can be dangerous to mix both error handling implementations as messages may be lost (i.e you get the Error.prototype.message and save it to a db, you'll get an undefined record if a throw "error" was triggered).Cony

© 2022 - 2024 — McMap. All rights reserved.