处理构造函数中的常规异常

时间:2015-04-12 05:18:15

标签: java

有没有办法在构造函数中处理异常。 每次我将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;
}

1 个答案:

答案 0 :(得分:0)

从构造函数中抛出它,并在其他任何地方处理它。当构造函数遇到异常情况时,抛出异常而不是继续并完全构造对象。

想象一下,如果FileInputStream没有抛出FileNotFoundException

FileInputStream fis = new FileInputStream("~/iDontReallyExist.bin");
// appears to work

// then later, long after you've instantiated `fis`
fis.read(buffer); // <-- boom?

构造函数可以而且应该在出现问题时抛出异常。调用构造函数的代码(或堆栈中的更高版本)按照他们认为合适的方式处理它(再次尝试,失败等)。作为奖励,half constructed object becomes available for garbage collection无需你太在意它。

假设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]));
}

在这个例子中,我将其记录在负责按类别加载问题的代码中,然后重新抛出它以让它爆炸。我选择这样做是因为无法打开本地文件似乎是致命的东西,但你并不局限于这样做。您可以简单地不在返回的结果中包含问题,或者要求使用不同的搜索路径。在错误上做什么的底线最终是在你需要的背景下。

相关问题