Throw'foo',throw Error('foo'),throw new Error('foo')和有什么区别? [英] What is the difference between `throw 'foo'`, `throw Error('foo')`, `throw new Error('foo')`?
问题描述
我已经看到了三种不同的JavaScript错误抛出方式:
I've seen 3 different ways of throwing an error in JavaScript:
throw 'message';
throw Error('message');
throw new Error('message');
它们之间有什么区别?
注意:我知道类似的问题( 1 , 2 ,3 等)。它们都不覆盖这三种情况。
Note: I am aware of similar questions (1,2,3, etc). None of them cover all three cases.
推荐答案
投掷
是表达式,它会暂停功能并生成例外。抛在 throw
之后的所有内容都作为异常传递。可以将其视为带有语法糖的函数,因此您无需编写 throw('message')
,而是编写 throw'message'
。 抛出新错误('message')
就像 throw'message'
一样,只是传递了一个对象而不是
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.
没有区别在引发错误('message')
和引发新错误('message')
之间:许多核心JavaScript对象允许在没有 new
构造函数的情况下创建新对象,而 Error
就是其中之一。
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.
话虽如此,您应该始终使用抛出新错误('message')
。 Error
对象包含堆栈跟踪和其他有用的调试信息,这些信息在您使用字符串文字时会丢失。使用ES6类创建对象需要使用 new
和通过类扩展 Error
是保留堆栈跟踪的唯一方法。创建自定义错误类可使错误处理更加统一。
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.
另请参见:极其精美的插图。
这篇关于Throw'foo',throw Error('foo'),throw new Error('foo')和有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!