我有一个声明会抛出大量已检查的异常。我可以像这样添加所有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...
我不喜欢这样,因为它们都是以相同的方式处理的,所以有一些代码重复,还有很多代码要编写。相反可以抓住Exception
:
try {
methodThrowingALotOfDifferentExceptions();
} catch(Exception ex) {
throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}
这没关系,除了我希望所有运行时异常都被丢弃而不会被捕获。这有什么解决方案吗?我当时认为要捕获的异常类型的一些聪明的通用声明可能会起作用(或者可能不是)。
答案 0 :(得分:42)
您可以执行以下操作:
try {
methodThrowingALotOfDifferentExceptions();
} catch(RuntimeException ex) {
throw ex;
} catch(Exception ex) {
throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}
答案 1 :(得分:13)
如果您可以使用Java 7,则可以使用Multi-Catch:
try {
methodThrowingALotOfDifferentExceptions();
} catch(IOException|ClassCastException|... ex) {
throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex);
}
答案 2 :(得分: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
。