抛出异常时的一个小问题

时间:2015-10-15 20:51:39

标签: java

我想问一下我在尝试创建一个可以从文件中读取文本的方法时遇到的问题。

例如,我创建了一个简单的界面,当您单击按钮时,将读取带有预定义文件夹路径的文本。

所以我像这样使用actionListener。请注意,“einlesen”是德语中的“阅读”。

public void actionPerformed(ActionEvent e)
{
    Object source = e.getSource();
    if (source == einlesenDatei)
    {
        this.einlesen();
    }
    if (source == decoder)
    {
        this.decode();
    }
}

问题是,readInput方法要求我抛出FileNotFoundException,而actionPerformed方法要求我切断抛出异常部分。

1 个答案:

答案 0 :(得分:2)

您可以将read方法的代码放在try catch块中,如下所示:

public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    if (source == inputFile) {
        try {
            this.readInput();
        } catch (FileNotFoundException e) {
            // handle the exception
        }
    }
    if (source == decoder) {
        this.decode();
    }
}