|
Previous Next
Must Handle Exceptions
There are some exceptions that Java forces you to deal with before it will compile the program.
The following example consists of reading a file called input.txt, which doesn't exist. File processing will be covered in a later session. Here we only want to demonstrate some compile errors that you will see if you don't handle the required exceptions. The compiler points to each of the statements that can cause an error and states that the exception must be caught.
import java.io.*;
public class FilesNoExcept {
public static void main(String[] arguments) {
File inFile = new File("input.txt");
FileInputStream in = new FileInputStream(inFile);
boolean eof = false;
while (!eof) {
int input = in.read();
if (input == -1)
eof = true;
else
System.out.println("Read in : " + input);
}
in.close();
}
}
When the compiler sees the code "new FileInputStream(inFile)", it knows that the file must exist before it can set up an input stream for it. It wants to force you to handle the possibility of getting the exception, FileNotFoundException.
When the compiler sees the code "in.read()" and "in.close()", it wants you to be prepared for IO exceptions that can occur as a result of reading the file and closing the file. The file can be corrupt and unreadable, or the CD or other removable media can be removed before the reading or closing of the file is complete, any other errors can occur. You need to handle the exception, IOException.
You don't have to handle FileNotFoundException if you handle IOException. The latter will catch both errors. However, if you want separate code for the FileNotFoundException, you can include it. Also, remember that you can use the general Exception to catch all errors. Then you don't have to be concerned with the specific conditions.
The corrected code might look like the following.
import java.io.*;
public class FilesNoExcept2 {
public static void main(String[] arguments) {
try {
File inFile = new File("input.txt");
FileInputStream in = new FileInputStream(inFile);
boolean eof = false;
while (!eof) {
int input = in.read();
if (input == -1)
eof = true;
else
System.out.println("Read in : " + input);
}
in.close();
} catch(FileNotFoundException e){
System.out.println("The file 'input.txt' does not exist."
+ " Exception : "+ e.getMessage());
} catch(IOException e){
System.out.println("IO Exception : "+ e.getMessage());
}
}
}
Previous Next
|