Exception Handling with a Datafile

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 and 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 as listed in the code; the first one matched 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 (think "permissions").

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.