Card 02/ 10

ExampleDifficulty: Beginner1 min

Opening a File That Is Not There

A path that was right yesterday. The call throws, and the message names the thing that was missing.

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

Two catch blocks, tried top to bottom, and the first matching type wins. 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.