我使用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();
}
由于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
无法抛出已检查的异常。。。。
在actionPerformed()方法内部,编写
customHandler.saveTransactionToFile();
像一样写
public void actionPerformed(ActionEvent event)
{
// Save transactions to file
if(event.getSource()== buttonSaveTransaction)
{
try
{
customHandler.saveTransactionToFile();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
要回答为什么必须这样做"这是因为被调用的方法,即customHandler.saveTransactionToFile();
,已知会抛出定义中提到的IOException。"
希望这将有助于
问候
将其包围在try-catch 中
try
{
if(event.getSource()== buttonSaveTransaction)
{
customHandler.saveTransactionToFile();
}
}
catch(IOException e)
{
//manage exception
}
您可以使用它,也可以通过hvgotcodes查看答案。
try {
customHandler.saveTransactionToFile();
} catch (IOException e) {
e.printStackTrace();
}