New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Java› Exceptions and Files

Exceptions and Files

💻 Java

Handle errors with try/catch and read or write text files safely.

Lesson 8 of 9 Tutorial
0 of 9 completed

Files fail, networks drop and users type the wrong thing. Java separates recoverable errors from programming bugs with exceptions.

By the end of this lesson you can:
  • Catch specific exceptions.
  • Use try-with-resources.
  • Read and write a text file.

try and catch

Catch the most specific exception first. Print a useful message, not just the stack trace, for expected problems.

try {
    int value = Integer.parseInt("not a number");
    System.out.println(value);
} catch (NumberFormatException error) {
    System.out.println("Please enter a whole number.");
}

try-with-resources

Files and other resources must be closed. try-with-resources closes them automatically, even when an exception occurs.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

try (BufferedReader reader = new BufferedReader(new FileReader("scores.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException error) {
    System.out.println("Could not read the file: " + error.getMessage());
}

Writing a File

Use Files.writeString for simple text output. It creates or replaces the file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;

try {
    Files.writeString(Path.of("output.txt"), "Amina,88\nBola,74\n");
} catch (IOException error) {
    System.out.println("Could not write the file.");
}
Tip Throw exceptions early with a clear message. A failure at the edge is easier to debug than a wrong value deep in the program.

Practice

  1. Handle invalid number input with try/catch.
  2. Read a file line by line and count the lines.
  3. Write two lines to a file and read them back.

Hands-on exercise

Write a program that reads scores.txt.
1. Print each line.
2. If the file does not exist, print 'No scores file found.'
3. Use try-with-resources so the reader always closes.

Recap

Catch expected failures, close resources automatically and give users a message they can act on.

Example

try {
    int value = Integer.parseInt("not a number");
    System.out.println(value);
} catch (NumberFormatException error) {
    System.out.println("Please enter a whole number.");
}

Exercises

Exercise 1. Safe file reader Medium
Write a program that reads scores.txt.
1. Print each line.
2. If the file does not exist, print 'No scores file found.'
3. Use try-with-resources so the reader always closes.
Java exercise-1.java
Expected Output
The file contents, or a friendly message when it is missing.

Lesson Nav

Lesson sections