相关疑难解决方法(0)

在Javascript中抛出自定义异常.使用哪种款式?

Douglas Crockford建议做这样的事情:

throw {
    name: "System Error",
    message: "Something horrible happened."
};
Run Code Online (Sandbox Code Playgroud)

但你也可以这样做:

function IllegalArgumentException(message) {
    this.message = message;
}

throw new IllegalArgumentException("Argument cannot be less than zero");
Run Code Online (Sandbox Code Playgroud)

然后做:

try {
    //some code that generates exceptions
} catch(e) {    
    if(e instanceof IllegalArgumentException) {
        //handle this
    } else if(e instanceof SomeOtherTypeOfException) {
        //handle this
    }
}
Run Code Online (Sandbox Code Playgroud)

我想你可以type在Crockford的实现中包含一个属性,然后检查它而不是做一个instanceof.做一个对另一个有什么好处吗?

javascript exception-handling exception custom-exceptions

23
推荐指数
1
解决办法
7736
查看次数