An IOException is thrown.
Most IO methods throw
an IOException
when an error is encountered.
A method that uses one of these IO methods
must either (1) include throws IOException
in its header, or (2) perform its IO in a
try{}
block and then catch
IOExceptions.
Here is the example program modified to catch exceptions:
import java.io.*; class WriteTextFile2 { public static void main ( String[] args ) { String fileName = "reaper.txt" ; try { // append characters to the file FileWriter writer = new FileWriter( fileName, true ); writer.write( "Alone she cuts and binds the grain,\n" ); writer.write( "And sings a melancholy strain;\n" ); writer.write( "O listen! for the Vale profound\n" ); writer.write( "Is overflowing with the sound.\n\n" ); writer.close(); } catch ( IOException iox ) { System.out.println("Problem writing " + fileName ); } } }
The constructor, the write()
method, and the close()
method
can throw an IOException.
All are caught by the catch
block.
The program opens the file reaper.txt for appending.
Run it and see what it does.
If you are running a Microsoft operating system, change the permissions of the file reaper.txt to read only. (Right-click on the file name in Explorer and then go to properties). Now run the program again. What happens?