22

多くのチェックされた例外をスローするステートメントがあります。次のように、すべてのキャッチブロックを追加できます。

try {
    methodThrowingALotOfDifferentExceptions();
} catch(IOException ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
} catch(ClassCastException ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
} catch...

これらはすべて同じように処理されるため、コードの重複があり、作成するコードも多いため、これは好きではありません。代わりにキャッチすることができExceptionます:

try {
    methodThrowingALotOfDifferentExceptions();
} catch(Exception ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}

すべてのランタイム例外をキャッチせずに破棄したい場合を除いて、それは問題ありません。これに対する解決策はありますか?キャッチされる例外のタイプの巧妙な一般的な宣言がうまくいくかもしれない(あるいはそうでないかもしれない)と私は考えていました。

4

3 に答える 3

50

次のことができます。

try {
    methodThrowingALotOfDifferentExceptions();
} catch(RuntimeException ex) {
    throw ex;
} catch(Exception ex) {
    throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}
于 2012-11-14T12:28:24.850 に答える
15

Java 7を使用できる場合は、マルチキャッチを使用できます。

try {
  methodThrowingALotOfDifferentExceptions();
} catch(IOException|ClassCastException|... ex) {
  throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}
于 2012-11-14T12:32:18.100 に答える
2

このようなことを試して、基本的にすべてをキャッチしてから、それがそのクラスのインスタンスである場合は再スローするRuntimeExceptionことができます...

try {
    methodThrowingALotOfDifferentExceptions();
} catch(Exception ex) {
    if (ex instanceof RuntimeException){
        throw ex;
    }
    else {
        throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
    }
}

これを何度も何度も書くのは面倒である(そして保守性に悪い)ように見えるので、おそらくコードを別のクラスに移動します。

public class CheckException {
    public static void check(Exception ex, String message) throws Exception{
        if (ex instanceof RuntimeException){
            throw ex;
        }
        else {
            throw new MyCustomInitializationException(message, ex);
        }
    }
}

そして、このようにあなたのコードでそれを使用してください...

try {
    methodThrowingALotOfDifferentExceptions();
} catch(Exception ex) {
    CheckException.check(ex,"Class Resolver could not be initialized.");
}

messageをカスタマイズできるように、を渡すことに注意してくださいMyCustomInitializationException

于 2012-11-14T12:50:10.563 に答える