【问题标题】:windowClosing() and throwing exceptionswindowClosing() 和抛出异常
【发布时间】:2014-04-06 10:24:08
【问题描述】:

我正在尝试在窗口(和脚本)关闭之前保存信息(将矢量保存到文件中)。我到处检查和搜索我找不到做什么。

我遇到的错误是

未报告的异常 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);
        }
    });

【问题讨论】:

  • 你为什么使用System.exit(0)?你觉得frame.dispose()怎么样?
  • @Braj 我也退出了应用程序,所以不确定 dispose 是否这样做
  • 阅读frame.dispose()方法。

标签: java swing exception file-io windowlistener


【解决方案1】:

问题在于main 方法中的这些代码行

try
{
   savePlayers();
}
catch (IOException ex) {
   ex.printStackTrace();              
}

改变它来捕捉

try
{
   savePlayers();
}
catch (Exception ex) {
   ex.printStackTrace();              
}

它会起作用的。您的 savePlayers() 方法抛出 Exception 而不是 IOException

以上将解决问题,但我不知道为什么你的 savePlayers() 方法在方法定义中有这个奇怪的throws Exception?您应该考虑将其删除,因为您的代码不会引发任何异常。如果是,请与您的IOException 一起处理。

【讨论】:

    【解决方案2】:

    将 savePlayers 方法更改为:

    static public void savePlayers() 
    

    或者,将窗口侦听器操作更改为:

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

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

    【讨论】:

    • 谢谢@suhe_arie,但我选择了第二个选项,我会在有更多时间时检查第一个选项。
    猜你喜欢
    • 2013-05-24
    • 2013-06-24
    • 2011-09-07
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多