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 asfileName
,lineNumber
andstack
. You only get these onError
objects and they can be very useful for debugging.
精彩评论