24

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
    }
}

typeCrockford の実装にプロパティを含めて、 instanceof. 一方を他方に対して行うことには利点がありますか?

4

2 に答える 2

4

コードの純度の点で再利用しやすいため、私は 2 番目のものを支持します。正確に言えば、複数の場所で同じ例外 (メッセージが異なる同じ例外タイプであっても) をスローしようとすると、最初のアプローチではコードが乱雑 (膨大) になります。

于 2012-10-25T21:46:08.560 に答える