Card 02/ 10

ExampleDifficulty: Beginner1 min

Catching Exceptions Example: Opening a File That Is Not There

A path that was right yesterday, and a message that names the missing file.

Several catch blocks are tried from top to bottom, and the first whose type matches the exception runs. Catching the specific type gives you the methods only that type has. A file path that was right yesterday:

java
try {
    String text = Files.readString(Path.of("config/rates.csv"));
    System.out.println(text.length());
} catch (NoSuchFileException e) {
    System.out.println("missing: " + e.getFile());
} catch (IOException e) {
    System.out.println("unreadable: " + e.getMessage());
}
text
missing: config/rates.csv

NoSuchFileException extends IOException, so the narrower one has to come first. Reverse them and the compiler refuses, because the second could never be reached.

The narrower type carried something the wider one does not. getFile() exists on NoSuchFileException and not on IOException, which is the whole reason to catch the specific type rather than the general one.

If the file exists but cannot be read, because of its permissions for example, the first catch does not match and the second one runs, printing the more general message.