1

我正在创建一个支票簿,但无法为每个单独的帐户创建要写入的文件。当我尝试创建文件时,我收到错误“未报告的异常 IOException;必须被捕获或声明为被抛出”。我尝试声明我的动作侦听器方法引发异常,但这使得动作侦听器方法不再能够工作。然后我尝试创建一个单独的方法来创建文件并通过按下按钮调用但我仍然遇到同样的错误

这是我的代码:

public void actionPerformed(ActionEvent e) {

    ...

    if (e.getSource() == create)  {
         creatNewAccount(name3.getText());
         BALANCE = Double.parseDouble(name2.getText());
    }
}
public void creatNewAccount(String s) throws IOException {
    FileWriter fw = new FileWriter(s + ".txt", false);
}
4

4 回答 4

2

IOException是一个检查异常。鉴于您在 a 中调用它ActionListener,重新抛出异常不是一种选择,因此您需要捕获它。

try {
   creatNewAccount(name3.getText());
} catch (IOException e) {
   e.printStackTrace();
   // more exception handling
}
于 2013-05-14T20:27:41.193 回答
2

creatNewAccount被声明为可能抛出一个IOException. IOException不是 a RuntimeException,所以你必须抓住它。

if (e.getSource() == create)  {
     try {
         creatNewAccount(name3.getText());
     } catch (IOException ie) {
         ie.printStackTrace();
         // handle error
     }
     BALANCE = Double.parseDouble(name2.getText());
}

有关更多信息,请阅读有关捕获或指定要求捕获和处理异常的信息。


我注意到的其他一些事情:-您要查找的词是create,而不是creat。- 你正在分配一些东西给BALANCE. 大写名称通常保留给常量。考虑重命名这个变量balance。- 为您的文本字段考虑更具描述性的名称。name2而且name3真的不多说。

于 2013-05-14T20:28:27.437 回答
1

在您的电话中actionPerformed(),您需要在createNewAccount呼叫周围放置一个 try/catch 块。一旦捕获到异常,您如何处理取决于您 - 一个简单的事情是将其包装在RuntimeException不需要被捕获的中(但可能会破坏您的过程,直到您做一些更复杂的事情)。

public void actionPerformed(ActionEvent e) {

    ...

    if (e.getSource() == create)  {
         try {
             creatNewAccount(name3.getText());
         } catch( IOException ioe) {
             System.err.println("Whoops! " + ioe.getMessage());
             throw new RuntimeException("Unexpected exception", ioe);
         }
         BALANCE = Double.parseDouble(name2.getText());
    }
}
于 2013-05-14T20:29:59.903 回答
1

您可能只需要在方法中捕获异常:

public void creatNewAccount(String s) {
    try{
        FileWriter fw = new FileWriter(s + ".txt", false);
    } catch (IOException e){
        //TODO something to handle the error
    }
}
于 2013-05-14T20:37:57.577 回答