我很好奇哪一個更實用,哪些情況下我們需要使用第一個,哪些需要使用第二個?例如,在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