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

为君一笑 提交于 2020-06-12 04:55:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/46295340/what-is-the-difference-between-throw-foo-throw-errorfoo-throw-new-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!