Java IOException
Example
Write to a file after it is closed, and catch the exception:
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.close();
myWriter.write("Hello World");
} catch (IOException e) {
System.out.println("Error: the file is already closed.");
}
}
}
Definition and Usage
An IOException happens when an input or output operation fails, for example when a file cannot be read or written, or when a stream (a flow of data to or from a file) is already closed.
It is a checked exception (Java requires you to catch it, or to declare it with throws). Many other exceptions are kinds of IOException, like FileNotFoundException.
Tip: Read more about files in our Java Files Tutorial.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions