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,则可以使用Multi-Catch

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 回答