是否有方法处理构造函数中的异常。每次在另一个方法中使用getter时,我都必须再次声明异常。我在构造函数中尝试了一个try/catch块,但仍然要求其他方法来声明异常。
public Question() {
try {
this.file = new File("questions.txt");
} catch (Exception e) {
System.out.println("Could not find file");
System.out.println("Check file path is correct");
}
counterIndex = 0;
questionSetup();
}
public Question() throws FileNotFoundException {
file = new File("questions.txt");
counterIndex = 0;
questionSetup();
}
public ArrayList<String> getQuestionArr() {
return questionArr;
}
public File getFile() {
return file;
}
从构造函数中抛出它,并在其他任何地方处理它。当构造函数遇到异常情况时,它应该抛出异常,而不是继续并完全构造对象。
想象一下,如果FileInputStream
没有抛出FileNotFoundException
。
FileInputStream fis = new FileInputStream("~/iDontReallyExist.bin");
// appears to work
// then later, long after you've instantiated `fis`
fis.read(buffer); // <-- boom?
构造函数可以并且应该在出现故障时抛出异常。调用构造函数(或堆栈中更高级别的构造函数)的代码可以根据自己的意愿处理它(重试、失败等)。作为奖励,半构建的对象可以用于垃圾收集,而无需过于担心。
假设Question()
抛出一个FileNotFoundException
,你可以处理这样的错误(我显然不了解你的真实应用程序,所以这是错误处理的一个例子):
Question loadQuestion(int id) throws FileNotFoundException {
return new Question(getQuestionPath(id));
}
调用方:
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;
}
最后是
public static void main(String[] args) throws FileNotFoundException {
Set<Questions> questions = QuestionsLoader
.getQuestionsByCategory(QuestionCategory.valueOf(args[0]));
}
在这个例子中,我将它记录在负责按类别加载问题的代码中,然后重新抛出它,让它爆炸。我之所以选择这样做,是因为无法打开本地文件在这里似乎是致命的,但你不必这么做。相反,您可以简单地不在返回的结果中包含问题,或者要求其他搜索路径。在出现错误时该做什么的底线最终取决于您需要什么。