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?