背景
我有一个案例,我的逻辑需要用 try/catch 包围,我有很多 catch 子句,这让我的代码有点难看。我在 catch 子句中所做的只是使用 log4j 记录错误。
问题
可以使用一个带有父异常类型的 catch 子句而不是一堆 catch 子句吗?而不是这个:
try{
//some statements
} catch (KeyStoreException e) {
LOGGER.error(e);
} catch (CertificateException e) {
LOGGER.error(e);
} catch (NoSuchAlgorithmException e) {
LOGGER.error(e);
} catch (FileNotFoundException e) {
LOGGER.error(e);
} catch (IOException e) {
LOGGER.error(e);
} catch (UnrecoverableKeyException e) {
LOGGER.error(e);
} catch (NoPropertyFoundException e) {
LOGGER.error(e);
}
使用 :
try{
//some statements
} catch (Exception e) {
LOGGER.error(e);
}
哪一个更好?