Try/Catch Block for Opening a Datafile
try
{
infile = new BufferedReader(new FileReader(inFileName));
}
catch (IOException e)
{
System.err.println("Error - cannot open input file " + inFileName);
return;
}
Another common way to write this code is to handle different kinds of
exceptions differently.
Look at the additional code (in bold) below that shows how to do this.
Handling Different Exceptions for Opening a Datafile
try
{
infile = new BufferedReader(new FileReader(inFileName));
}
catch (FileNotFoundException e)
{
System.err.println("Error - input file " + inFileName + " not found.");
return;
}
catch (IOException e)
{
System.err.println("Error - cannot open input file " + inFileName);
return;
}
-
Remember, all classes in Java are part of a class hierarchy.
- The top-most class
is Object, so you would say that Object is the super class of all
other classes. Exceptions are also grouped into a hierarchy.
- A FileNotFoundException is a kind of IOException, so IOException
is the parent class and FileNotFoundException is the child class.
- Exception types are matched in order from the first catch to the last; the first one is executed.
- Note: To test this, run on a Linux system, not Windows. Some operating
systems, such as UNIX, allow a file to exist, but not be readable. In this
case, the file would be found but could not be opened, so an IOException
would be thrown. Not
all operating systems allow files that are unreadable. Windows does not, so
if you are running on a Windows system, you will always get a
FileNotFoundException because this is the only kind of problem with opening
the file you can have.