我试图在窗口(和脚本)关闭之前保存信息(将 vector 保存到文件中)。我到处检查和搜索,但找不到该做什么。
我遇到的错误是
unreported exception java.lang.exception; must be caught or declare to be thrown savePlayers().
但是我使用的是 loadPlayers
,它的作用相反,并且我对异常没有任何问题。请帮助任何人吗?代码是:
static public void savePlayers() throws Exception
{
//serialize the List
try
{
FileOutputStream file = new FileOutputStream(FILE_NAME);
ObjectOutputStream output = new ObjectOutputStream(file);
output.writeObject(players);
output.close();
}
catch(IOException ex)
{
System.out.println (ex.toString());
}
}
public static void main (String[] args) throws Exception
{
JFrame frame = new JFrame("Teams");
frame.setSize(700,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e)
{
try
{
savePlayers();
}
catch (IOException ex) {
ex.printStackTrace();
}
System.exit(0);
}
});
最佳答案
问题出在 main
方法中的这些代码行
try
{
savePlayers();
}
catch (IOException ex) {
ex.printStackTrace();
}
将其更改为捕获
try
{
savePlayers();
}
catch (Exception ex) {
ex.printStackTrace();
}
它会起作用的。您的 savePlayers()
方法抛出 Exception
而不是 IOException
。
上面的方法可以解决这个问题,但我不知道为什么你的 savePlayers() 方法在方法定义中有这个奇怪的 throws Exception
?您应该考虑删除它,因为您的代码不会引发任何异常。如果是,请将其与 IOException
一起处理。
关于java - windowClosing() 并抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892760/