是否可以捕获除运行时异常之外的所有异常?

我有一个语句,它抛出了很多检查的异常。我可以像这样为它们添加所有捕获块:

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

这没关系,除了我希望所有运行时异常都被丢弃而不会被捕获。有什么解决方案吗?我在想,一些聪明的通用声明要捕获的异常类型可能会起作用(或者可能不会)。


答案 1

您可以执行以下操作:

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

答案 2

如果您可以使用 Java 7,则可以使用多捕获

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