3

I have a class called Dictionary which reads constant-length-delimited words from a text file and creates a TreeSet from them for looking up whether or not a word exists in the dictionary.

So I obviously need to handle an IOException somehow. My question is, should the error-handling responsibilities fall upon the Dictionary class, or should it fall upon the code creating a Dictionary object?

Here's what I have:

public class Dictionary
{
    private final TreeSet<String> stringSet = new TreeSet<>();

    // constructor
    public Dictionary(String fileName) throws IOException
    {
        try (final Reader reader = new InputStreamReader(new FileInputStream(fileName)))
        {
            // load dictionary into stringSet
            final char[] buffer = new char[4];
            int numRead = -1;
            while ((numRead = reader.read(buffer)) > 0)
                stringSet.add(new String(buffer, 0, numRead).toUpperCase());
        }
        catch (IOException e)
        {
            throw e;
        }
    }

    public boolean contains(String word)
    {
        return stringSet.contains(word);
    }
}

And the code that creates a Dictionary object:

public class MainClass
{
    public static void main(String args[])
    {
        String fileName = "C:/Users/Brandon/Desktop/Android Development/Practice Apps/SwapWords_Prototype/src/data/dictionary.txt";
        try
        {
            Dictionary dict = new Dictionary(fileName);
        }
        catch (IOException e)
        {
            System.out.println("Could not load dictionary <" + fileName + ">");
            e.printStackTrace();
        }

        // TODO handle dict
    }
}

Should Dictionary catch and handle the IOException or throw it to the calling code? I mean, either one works, but which is more logical?

4

1 回答 1

2

I'd say that the way you have it set up right now is good as is. If it is the case that when Dictionary encounters an IOException, there isn't any good way for it to recover, then you will want to alert the caller that this failure occurred. If, on the other hand, Dictionary could gracefully handle the error on its own (by trying to load a different file or something), then you could put the code in the constructor to hide it from the caller.

What you don't want is for the caller to make a Dictionary that is internally invalid due to an exception, but looks completely fine to the caller.

于 2013-03-30T23:45:00.797 回答