1

我正在处理 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);
            }
4

2 回答 2

5

在 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);
    }
}

请参阅“捕获多个异常”。

于 2012-07-08T21:23:42.150 回答
0

这个答案从 Java 7 开始就已经过时了。像 John Watts 在他的答案中展示的那样使用 multi-catch。

我建议使用

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);
    }
}
于 2012-07-08T21:48:20.037 回答