Douglas Crockford 建议这样做:
throw {
name: "System Error",
message: "Something horrible happened."
};
但你也可以这样做:
function IllegalArgumentException(message) {
this.message = message;
}
throw new IllegalArgumentException("Argument cannot be less than zero");
然后做:
try {
//some code that generates exceptions
} catch(e) {
if(e instanceof IllegalArgumentException) {
//handle this
} else if(e instanceof SomeOtherTypeOfException) {
//handle this
}
}
我想你可以type
在 Crockford 的实现中包含一个属性,然后检查它而不是做一个instanceof
. 做一个与另一个相比有什么优势吗?