Eclipse中未处理的异常类型IOException

时间:2012-01-27 16:29:43

标签: java eclipse

我使用Eclipse编写代码,并在customHandler.saveTransactionToFile();处得到一个红色下划线,并显示

  

未处理的exeption类型IOException。

为什么会发生这种情况,我该如何解决?

// Call method in customHandler class to write to file when button is pressed
public void actionPerformed(ActionEvent event)
{
    // Save transactions to file
    if(event.getSource()== buttonSaveTransaction)
    {
         customHandler.saveTransactionToFile();
    }
}

// Method in class customHandler that writes to file
public void saveTransactionToFile() throws IOException
{
    System.out.println("Skriver till fil");
    File outFile = new File("C:/JavaBank/" + selectedCustomerAccountNumber + ".data");
    FileOutputStream outFileStream = new FileOutputStream(outFile);
    PrintWriter outStream = new PrintWriter(outFileStream);
    outStream.println("test");
    outStream.close();  
}

4 个答案:

答案 0 :(得分:3)

因为saveTransactionToFile抛出异常,actionPerformed调用该方法,需要捕获并处理它。

public void actionPerformed(ActionEvent event)
{
    // Save transactions to file
    if(event.getSource()== buttonSaveTransaction)
    {
         try {
             customHandler.saveTransactionToFile();
         } catch(IOException e) { 
             // I broke, make sure you do something here, so the user
             // knows there was an error
         }
    }
}

请注意,您需要在此处(或saveTransactionToFile)处理异常。 actionPerformed无法抛出已检查的异常....

答案 1 :(得分:2)

在你的actionPerformed()方法中,写一下

customHandler.saveTransactionToFile();

写这个像

public void actionPerformed(ActionEvent event)
{
    // Save transactions to file
    if(event.getSource()== buttonSaveTransaction)
    {
        try
        {
            customHandler.saveTransactionToFile();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
   }
}

要回答为什么必须这样做“这是因为调用ie customHandler.saveTransactionToFile();的方法已知会抛出定义中提到的IOException。” < / p>

希望有所帮助

此致

答案 2 :(得分:1)

尝试捕捉

try
{
    if(event.getSource()== buttonSaveTransaction)
    {
         customHandler.saveTransactionToFile();
    }
}
catch(IOException e)
{
 //manage exception 
}

答案 3 :(得分:0)

您可以使用此功能,也可以通过hvgotcodes查看答案。

try {
    customHandler.saveTransactionToFile();
} catch (IOException e) {
    e.printStackTrace();
}