Exceptions and Files
💻 JavaHandle errors with try/catch and read or write text files safely.
Files fail, networks drop and users type the wrong thing. Java separates recoverable errors from programming bugs with exceptions.
- 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.");
}Practice
- Handle invalid number input with try/catch.
- Read a file line by line and count the lines.
- 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
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.
Expected Output
The file contents, or a friendly message when it is missing.
Lesson Nav
Java Course
0/9 lessons completed
- 1 Getting Started with Java Tutorial
- 2 Variables and Data Types Tutorial
- 3 Conditions and Loops Tutorial
- 4 Methods and Parameters Tutorial
- 5 Arrays and ArrayLists Tutorial
- 6 Classes and Objects Tutorial
- 7 Inheritance, Interfaces and Polymorphism Tutorial
- 8 Exceptions and Files Tutorial
- 9 Project: A Console Grade Book Project