我很好奇哪一个更实用,哪些情况下我们需要使用第一个,哪些需要使用第二个?例如,在Java7:在Try块中,为多个异常创建一个Catch还是为每个异常创建一个Catch更好?
first.java
try {
/* some code that throws these exceptions */
} catch (NoSuchAuthorityCodeException e) {
throw new MyAPIException("Something went wrong", e);
} catch (FactoryException e) {
throw new MyAPIException("Something went wrong", e);
} catch (MismatchedDimensionException e) {
throw new MyAPIException("Something went wrong", e);
} catch (TransformException e) {
throw new MyAPIException("Something went wrong", e);
}
second.java
try {
/* some code that throws these exceptions */
} catch (NoSuchAuthorityCodeException | FactoryException| MismatchedDimensionException | TransformException e) {
/*handle all exceptions*/;
}
这要看情况。你是否希望每个错误都发生同样的事情,还是每个错误都需要一个特定的错误? –
@Mena他们都可以被命名为'e',在这种情况下这不是问题。 – JonK