Throw both the main exception and the subtype, is there a proper way?

Okay, so I have a bunch of questions related to exceptions among SO and Programmers, but there is so much to ask, and either I don’t know what to enter, or not many people asked.

So, let's say I have a method that generates FileNotFoundException(FNFE). Then I have another method that uses the first, but also throws IOException(IOE).

My handler would catch both of them with each, but my IDE (IntelliJ) signals that I have a "more general exception," java.io.IOException, in the list of throws already. "

I know this works if I do this:

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;

}

? .

, , :

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

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

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

}

, , FNFE, ? , .

+4
5

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
} 
+4

FileNotFoundException throws, IOException.

. FileNotFoundException , ( , , catch IOException).

IOException throws , IOException . FileNotFoundException .

+1

? , .

. , .


: , , throws , throws IOException, .

: n , IOException, . .close() , . .

, , , , .

, , , , , .

0

Java :

V , (. 5.2), catch try, , ( ) catch. V catch, catch , :...

( ).

Therefore, if you want your more specific sentence to be catchexecuted, you must first put it in the catch list.

0
source

you can catch a subclass exception first, if not, then a generic exception class like this

try{
      // something
   } catch(FileNotFoundException fne){
      // Handle the exception here
   } catch(IOException ioe) {
      // Handle the IOException here
   }
-2
source

Source: https://habr.com/ru/post/1609307/


All Articles