Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 781
Indolering Avatar asked Sep 19 '17 08:09

Indolering


People also ask

What does throw new error do in JavaScript?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

Does throw new error stop execution?

throw new Error('something went wrong') — will create an instance of an Error in JavaScript and stop the execution of your script, unless you do something with the Error.


1 Answers

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.

like image 194
Indolering Avatar answered Oct 05 '22 06:10

Indolering