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

Ras*_*sto 21 java generics exception try-catch runtimeexception

我有一个声明会抛出大量已检查的异常.我可以为所有这些添加所有catch块,如下所示:

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...
Run Code Online (Sandbox Code Playgroud)

我不喜欢这样,因为它们都是以相同的方式处理的,所以有一些代码重复,还有很多代码要编写.相反可以抓住Exception:

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

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

bdo*_*han 46

您可以执行以下操作:

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

  • +1酷.我见过的不是最干净但是诀窍. (2认同)

Urs*_*pke 13

如果可以使用Java 7,则可以使用Multi-Catch:

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