Java NoSuchFileException and IOException
A missing receipt can have a normal explanation: nobody has saved it yet. Catch NoSuchFileException for that case and let other I/O failures reach the caller.
A simple example
NoSuchFileException and IOException
- Start with No file named a.txt
- Do this Open a.txt for reading
- Result File missing
Syntax
try { Files.readString(path); }
catch (NoSuchFileException missing) { /* report the missing receipt */ }
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaLook for a receipt in a new folder
A clerk requests a receipt before a new folder contains any exports. Handle that missing entry explicitly so the application can give the clerk a useful next action.
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws Exception {
Path folder = Files.createTempDirectory("receipts-");
try {
Path receipt = folder.resolve("today.txt");
System.out.println(Files.readString(receipt));
} catch (NoSuchFileException missing) {
System.out.println("No receipt saved for today");
} finally {
Files.deleteIfExists(folder);
}
}
}
No receipt saved for today
The directory is new and empty, so today.txt is missing. Other I/O errors propagate out of main. The finally block removes the empty temporary directory.
Recover a missing menu without hiding other errors
A café opens a new folder for each day’s lunch menu. If the menu has yet to be published, the counter displays its regular menu and leaves other file errors for the manager to investigate.
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
class Main {
public static void main(String[] args) throws Exception {
var desk = Files.createTempDirectory("menu-");
try {
System.out.println(Files.readString(desk.resolve("lunch.txt")));
} catch (NoSuchFileException absent) {
System.out.println("Show the regular menu");
} finally {
Files.delete(desk);
}
}
}
Show the regular menu
Catching the specific missing-entry exception lets other I/O failures propagate.
Read a saved shift record
The closing clerk saved the file before leaving. Open the expected file and show the desk whether it is available.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
Path dir=Files.createTempDirectory("lesson-");
Path file=dir.resolve("record.txt");
try {
Files.writeString(file,"Ready");
Files.readString(file);
System.out.println("File available");
} catch (NoSuchFileException e) {
System.out.println("Ask for the file");
} finally {
Files.deleteIfExists(file);
Files.deleteIfExists(dir);
}
}
}
File available
What to watch for
IOException is the broader checked exception. If you handle both in separate catch blocks, put NoSuchFileException first.