← Java

Java · 09 / 18

Exceptions and safe file access

Handle a failure and close a file even when work stops.

  • Small
  • Basics
  • 15 min

Prerequisites: Interfaces and composition

An exception signals that normal processing could not continue. try marks a protected workflow. catch handles a matching error. Resources such as open files must be closed again. try-with-resources does this reliably even if an error occurs during processing.

Example files

01Create a safe sample file

Save sample.txt containing two names in the learning folder. We read only this file. Path.of describes its path. A relative path refers to the current working directory rather than automatically to the Java source directory.

sample.txt · textOpen file
Ada
Lin

02Open a resource

Files.newBufferedReader opens a text reader. UTF_8 specifies character encoding. The resource appears inside the parentheses following try. Java calls close when leaving the block. readLine returns null at end of file.

Main.java · javaOpen file
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
  public static void main(String[] args) {
    try (var reader = Files.newBufferedReader(Path.of("sample.txt"), StandardCharsets.UTF_8)) {
      String line;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
    } catch (IOException error) {
      System.err.println("Cannot read sample: " + error.getMessage());
    }
  }
}

Run / check

java Main.java

03Trigger the error path

Rename sample.txt and run again. IOException is handled. A failure differs from an empty file. A real interface should give distinguishable feedback for these two cases.

Expected result

Ada and Lin appear. Without the file, an error message appears.

Your exercise

Count the lines read and print the count at the end.

Show the solution and explanation

Declare int count = 0 inside try before the loop, increment it for each line and print it after the loop. The sample file produces 2. Blank lines also count as lines read.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.