Java IOException
IOException is the checked exception family for failed I/O operations. BufferedReader.readLine can throw it when the reader has already been closed.
A simple example
IOException
- Start with A reader has already been closed
- Do this Try another read
- Result Read fails
Syntax
reader.readLine()
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead from a finished receipt import
A receipt importer closes its reader at the end of a batch. If the preview screen asks for another line through that reader, the application needs to detect the stale handle and open a new reader for the next batch.
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
class Main {
public static void main(String[] args) throws Exception {
var reader = new BufferedReader(new StringReader("Receipt 42"));
reader.close();
try {
System.out.println(reader.readLine());
} catch (IOException closed) {
System.out.println("Open a new reader");
}
}
}
Open a new reader
The source text is still available, but this reader has finished its lifecycle. A fresh reader is required.
Preserve the cause when a preview fails
A shop's preview screen reads from a receipt reader that the importer has already closed. Its caller needs a useful application-level failure while the underlying I/O cause remains available for diagnostics.
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
import java.io.UncheckedIOException;
class Main {
public static void main(String[] args) throws Exception {
var reader = new BufferedReader(new StringReader("Receipt"));
reader.close();
try {
reader.readLine();
} catch (IOException cause) {
var failure = new UncheckedIOException("Receipt preview failed", cause);
System.out.println(failure.getCause().getClass().getSimpleName());
}
}
}
IOException
UncheckedIOException retains the original checked IOException as its cause.
Read the first rehearsal note
The music desk has just opened a reader containing a short note. Read the next character from the stream. A previously closed stream prompts the desk to reopen the source.
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 {
try {
try (var reader=new StringReader("Tune")) { reader.read(); }
System.out.println("Read succeeded");
} catch (IOException problem) {
System.out.println("Reopen source");
}
}
}
Read succeeded
What to watch for
An IOException can have many causes. A general handler should retain the original exception when passing the failure onward.