开发者

What type of exception should be thrown in JavaScript?

What type of object should be thrown in JavaS开发者_运维百科cript?

I see a lot of examples which throw a plain old string and there seems to be a semi-standard Error type. Should I prefer one over the other?


The Error object and specific error objects such as TypeError are fully standardized in the ECMAScript specification. There are, however, common non-standard properties of these objects available in most browsers.

You can throw whatever you like, so long as your error handling code knows what to do with the objects you throw, but there are advantages to using Error objects:

  • Consistency with handling errors thrown by native code, such as having a message property, so you don't have to write different code to handle native errors and your own errors;
  • Error objects in Mozilla and other browsers have very useful non-standard properties, such as fileName, lineNumber and stack. You only get these on Error objects and they can be very useful for debugging.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜