我正在处理JaudioTagger API来操作MP3文件,我不得不一遍又一遍地重复以下异常...我正在考虑使用通用异常处理程序,我可以使用标志号转发每个异常并且通用方法可以通过使用不同的开关案例来处理它吗?可能吗 ?如果有人能给出方法签名或者称之为方法
,我真的很感激} catch (CannotReadException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (ReadOnlyFileException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidAudioFrameException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (TagException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
答案 0 :(得分:5)
Pre-JDK 7你所能做的就是编写一个实用函数并从每个catch块中调用它:
private void handle(Exception ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
private void someOtherMethod() {
try {
// something that might throw
} catch (CannotReadException ex) {
handle(ex);
} catch (ReadOnlyFileException ex) {
handle(ex);
} catch (IOException ex) {
handle(ex);
} catch (InvalidAudioFrameException ex) {
handle(ex);
} catch (TagException ex) {
handle(ex);
}
}
从JDK 7开始,您可以使用multi-catch:
private void someOtherMethod() {
try {
// something that might throw
} catch (CannotReadException | ReadOnlyFileException | IOException
| InvalidAudioFrameException | TagException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
答案 1 :(得分:0)
从Java 7开始,这个答案已经过时了。在他的回答中使用像John Watts这样的多重捕捉。
我建议使用
try {
/* ... your code here ... */
} catch (Exception ex) {
handle(ex);
}
并以这种方式处理:(你必须替换你不处理的OtherException或删除throws
)
private static void handle(Exception ex) throws SomeOtherException {
if (ex instanceof CannotReadException || ex instanceof ReadOnlyFileException) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
} else if (ex instanceof SomeOtherException) {
throw (SomeOtherException) ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new RuntimeException(ex);
}
}