Throw it from the constructor, and handle it anywhere else. When a constructor encounters an exceptional situation, it should throw an exception instead of continuing along and fully constructing an object.
Imagine if FileInputStream
didn't throw a FileNotFoundException
.
FileInputStream fis = new FileInputStream("~/iDontReallyExist.bin");
// appears to work
// then later, long after you've instantiated `fis`
fis.read(buffer); // <-- boom?
Constructors can and should throw exceptions whenever something breaks. Code calling the constructor (or higher up in the stack) handle it as they see fit (trying again, failing, etc.). As a bonus, the half constructed object becomes available for garbage collection without you needing to be too concerned about it.
Assuming that Question()
throws a FileNotFoundException
, you can handle an error something like this (I don't know your real app obviously, so this is made up as an example of error handling):
Question loadQuestion(int id) throws FileNotFoundException {
return new Question(getQuestionPath(id));
}
called by:
Set<Question> getQuestionsByCategory(QuestionCategory category) {
Set<Integer> ids = getQuestionIds(category);
Set<Question> questions = new HashSet<Question>();
for (Integer id : ids) {
try {
questions.add(loadQuestion(id));
} catch (FileNotFoundException ex) {
somelogger("File not found loading question ID " + id, ex);
throw ex;
}
}
return questions;
}
and finally
public static void main(String[] args) throws FileNotFoundException {
Set<Questions> questions = QuestionsLoader
.getQuestionsByCategory(QuestionCategory.valueOf(args[0]));
}
In this example, I log it in code responsible for loading questions by category, then re-throw it to let it blow up. I chose to do that because not being able to open a local file seems like something fatal here, but you're not constrained to do that. You could instead simply not include the question in the returned results, or ask for a different path to search. The bottom line of what to do upon an error is ultimately in context of what you need.