java - windowClosing() 并抛出异常

标签 java swing exception file-io windowlistener

我试图在窗口(和脚本)关闭之前保存信息(将 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/

相关文章:

c++ - 使用 std::unique_ptr 有什么好处吗?

javascript - webEngine.executeScript();抛出异常

java - 富有表现力的 Java 函数

java - AlarmManager/BroadcastReceiver 不工作

java - 如何只设置 JPanel 的左坐标和宽度?

java - Microsoft][ODBC 驱动程序管理器] 字符串或缓冲区长度无效

java - 停留在 Java 中的对象范围

java - Spring数据存储库查询包含的集合

java - 如何自动调整JSplitPane?

c++ - 处理程序抛出异常后是否需要重置 asio::io_service ?