Java 在构造函数中处理一般异常
是否有方法处理构造函数中的异常。 每次在另一个方法中使用getter时,我都必须再次声明异常。我在构造函数中尝试了一个try/catch块,但仍然要求其他方法来声明异常Java 在构造函数中处理一般异常,java,Java,是否有方法处理构造函数中的异常。 每次在另一个方法中使用getter时,我都必须再次声明异常。我在构造函数中尝试了一个try/catch块,但仍然要求其他方法来声明异常 public Question() { try { this.file = new File("questions.txt"); } catch (Exception e) { System.out.println("Could not find file"); S
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 召集人:
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]));
}
在本例中,我将它登录到负责按类别加载问题的代码中,然后重新抛出它,让它爆炸。我之所以选择这样做,是因为无法打开本地文件在这里似乎是致命的,但您不必这样做。相反,您可以简单地不在返回的结果中包含问题,或者请求不同的搜索路径。在错误发生时应该做什么的底线最终取决于您需要什么 AFAIK构造函数处理try-catch块就像处理其他代码一样。你确定你把try-catch放在了正确的位置吗?是的,第一个有try-catch/block,第二个没有,但是不确定它的位置是否正确。在这个例子中为什么有两个相同的构造函数?我不明白如果您有一个try-catch块,为什么它会要求您声明异常?你能发布让你这么做的代码吗?第一个只是显示我把try-and-catch块放在哪里,第二个没有。在我的类中只有一个,这是否意味着我使用第二个构造函数,然后使用try/catch块到另一个方法中,在这里使用getter并在那里处理它??。谢谢你的输入,经过30天的阅读,汉克终于明白了你想说什么。顺便说一句,为什么我不能给荣誉
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]));
}