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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With