在这里学习Java的家伙。我在学校有一个任务,我们用一些简单的 GUI 制作了一个小小的星球大战游戏。在我的SaveToFile()
方法和ReadFromFile()
方法中,我的方法抛出异常。这没关系,一切正常。
但在作业中它说:“某些方法可能会抛出异常。这些需要合理处理。” 我不明白这是什么意思。它显然与试图避免代码重复有关。有人有任何提示吗?是为错误制定一种可以重用的方法吗?
这是我的代码:
private void readFromFile()
{
try{
gui.makeInVisible();
FileInputStream fis = new FileInputStream("Savegame.obj");
ObjectInputStream ois = new ObjectInputStream(fis);
Battleground battleground = (Battleground) ois.readObject();
GUI gui = new GUI(battleground);
BattleController bc = new BattleController(gui, battleground);
ois.close();
}
catch (IOException e) {
gui.updateActionField("Something went wrong... Did you delete the file Savegame.obj while playing?");
e.printStackTrace();
}
catch (ClassNotFoundException f) {
System.out.println("Woops. This game looks broken! Did you delete the whole battleground class?");
}
}
private void saveToFile() { try{ // Serialize data object to a file ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Savegame.obj")); out.writeObject(battleground);
Serialize data object to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e) {
gui.updateActionField("Something went wrong with saving the file. And we really don´t know what I am afraid!");
}
}
谢谢。