Java windowClosing()并引发异常

Java windowClosing()并引发异常,java,swing,exception,file-io,windowlistener,Java,Swing,Exception,File Io,Windowlistener,我试图在窗口(和脚本)关闭之前保存信息(向量到文件)。我找遍了所有找不到该做什么的地方 我犯的错误是 未报告的异常java.lang.exception;必须被抓住或宣布 被抛出savePlayers() 然而,我使用的是loadPlayers,它的作用正好相反,我没有任何异常问题。有人要帮忙吗?代码是: static public void savePlayers() throws Exception { //serialize the List try

我试图在窗口(和脚本)关闭之前保存信息(向量到文件)。我找遍了所有找不到该做什么的地方

我犯的错误是

未报告的异常java.lang.exception;必须被抓住或宣布 被抛出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()方法在方法定义中有这个奇怪的
抛出异常
?您应该考虑删除它,因为您的代码不会引发任何异常。如果是,请将其与您的
IOException

一起处理,将savePlayers方法更改为:

static public void savePlayers() 
或者,将窗口侦听器操作更改为:

@Override
    public void windowClosing(WindowEvent e)
    {
        try
        {
            savePlayers();
        }
        catch (Exception ex) {
             ex.printStackTrace();              
        }
        System.exit(0);
    }

第一个选项更好,因为您实际上不需要在savePlayers()中抛出异常。

为什么要使用
System.exit(0)
?您对
frame.dispose()
有何看法?@Braj我也退出了应用程序,所以不确定dispose是否会退出。请阅读
frame.dispose()
方法。谢谢@suhe_arie,但我选择了第二个选项,我会在有更多时间时检查第一个选项。