道格拉斯·克罗克福德建议像这样做:
但您也可以像这样做:
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
}
}
我猜你可以在Crockford的实现中包含一个type
属性,然后检查它而不是使用instanceof
。从执行效果上来说,这两种方法是否有优劣之分呢?