I'm trying to save information (a vector to a file) before the window (and script) is closed. I have check and search everywhere I can't find what to do.
The Error I'm having is
unreported exception java.lang.exception; must be caught or declare to be thrown savePlayers().
However I'm using loadPlayers
which do the opposite and I don't have any problem with Exceptions. Help anyone please? The code is:
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);
}
});
The issue is with your these lines of code in main
method
try
{
savePlayers();
}
catch (IOException ex) {
ex.printStackTrace();
}
Change it to catch
try
{
savePlayers();
}
catch (Exception ex) {
ex.printStackTrace();
}
It will work. Your savePlayers()
method throws Exception
not IOException
.
The above will fix the issue but I don't know why your savePlayers() method have this strange throws Exception
in method definition? You should think to remove it, as your code not throwing any exception. If it is, handle it along with your IOException
.