Java Arena
Step 4 of 9

When the file is missing

A program that reads a file depends on something outside itself: the file might not be there, it might have another name, or it might be in another folder. Java knows this, and it doesn't even compile code that opens a file without saying what to do if that fails:

import java.nio.file.Paths;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(Paths.get("notes.txt"));
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
    }
}
What javac prints
Main.java:6: error: unreported exception IOException; must be caught or declared to be thrown
        Scanner scanner = new Scanner(Paths.get("notes.txt"));
                          ^
1 error

An IOException is a failure in reading or writing data (I/O is short for input and output). Most exceptions, such as the NumberFormatException from module 16, can happen without warning; this kind is one that Java makes you plan for. catch is the plan. (The other option in the message, declaring it, comes later in the course.)

try and catch

The try block holds the code that might fail. If a line in it throws an exception, Java leaves the try block right there and runs the catch block, instead of crashing. After the catch block, the program goes on as usual. Here there's no file prices.txt at all:

import java.nio.file.Paths;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Reading the prices...");
        try (Scanner scanner = new Scanner(Paths.get("prices.txt"))) {
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
            System.out.println("All prices read");
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
        System.out.println("Bye!");
    }
}
Output
Reading the prices...
Error: prices.txt
Bye!
  • catch (Exception e) catches any exception. e is a variable that holds the exception, and e.getMessage() is its message. A missing file throws a NoSuchFileException, whose message is just the file's name: that's why the program prints Error: prices.txt. Your own text in the catch block, such as Could not open prices.txt, can say more.
  • All prices read isn't printed: the rest of the try block is skipped.
  • Bye! is printed: after the catch block, the program carries on.

A message instead of a crash

catch (Exception e) catches every exception thrown inside its try block, not only the file's. A try without parentheses works for code that opens nothing:

try {
    int number = Integer.valueOf("12a");
    System.out.println("Got " + number);
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}
System.out.println("Still running");
Output
Error: For input string: "12a"
Still running

Without the try, the same line would crash the program with a NumberFormatException, as in module 16: Java's report, and nothing after it runs. With catch, your program decides what to say and keeps going.

Your task

Challenge 1 of 3

Fill in the blanks. The program prints the lines of menu.txt. When the file can't be read, it prints Could not read the file: and the error's message instead, so without the file it prints Could not read the file: menu.txt (one of the tests gives no file). For the file shown below, it prints:

tomato soup
pasta
apple pie

Challenge 2

The file visitors.txt has a line for each visitor of a museum. Print how many visitors there were, as Visitors: and the number. If the file can't be read, print only No visitor data. For the file shown below, the program prints:

Visitors: 4

Challenge 3

What does this program print? Follow it into the catch block, and out again.