抛出主要异常和子类型,是否有正确的方法?

Kal*_*lec 5 java exception-handling

好的,所以我在SO和程序员之间有一堆与异常相关的问题,但是有很多要问的问题,或者我不知道要输入什么,或者不是很多人问的.

所以,假设我有一个抛出FileNotFoundException(FNFE)的方法.然后我有另一个方法使用第一个,但也抛出一个IOException(IOE).

我的处理程序会同时捕获它们并对每个执行不同的操作,但是我的IDE(IntelliJ)发出信号,我已经在"抛出列表中有一个更普遍的例外,'java.io.IOException'".

我知道如果我这样做会有效:

public File openOrCreate(String pathStr) throws FileNotFoundException,
                                                IOException {
    try {

        // Method that generates the FNFE
        Path path = ReposioryProposition.getPath(pathStr);
        File file = path.toFile();

    catch (FileNotFoundException fnfe) {
        throw fnfe;
    }

    if (!file.exists())
        file.createNewFile();  // IOE
    return file;

}
Run Code Online (Sandbox Code Playgroud)

但我需要明确地做吗?它会没有工作,或者更危险的是,将有时没有明确的版本.

为了确保我们在同一页面,这是我最初编写的东西:

public File openOrCreate(String pathStr) throws FileNotFoundException,
                                                IOException {

    Path path = ReposioryProposition.getPath(pathStr);
    File file = path.toFile();

    if (!file.exists())
        file.createNewFile();
    return file;

}
Run Code Online (Sandbox Code Playgroud)

但我不确定会发生什么,是FNFE被抛出还是被吞没了?我的目的是分别抓住它们并为另一个做不同的事情.

Hoo*_*pje 6

您只需在throws列表中包含更常规的例外.这已经指定该方法可以抛出此异常的任何子类.

特别是,您必须处理更一般的异常,并且此异常处理程序也将处理子类.如果要显式处理子类,则必须在更一般的异常之前捕获它:

try {
    ...
} 
catch (FileNotFoundException e) {
    // handle subclass
}
catch (IOException e) {
    // handle general exception (this will not be executed if the
    // exception is actually a FileNotFoundException
} 
Run Code Online (Sandbox Code Playgroud)