我有一个需要在启动时加载数据的程序。数据来自序列化对象。我有一个方法loadData()
,在构造Data
类时调用它。有时,(即在丢失saveData之后,或者在新系统上首次启动程序时),该文件可能为空。 (文件将存在,方法确保)。
当我尝试运行程序时,我收到了一个EOFException。因此,在该方法中,我尝试捕获它,只是在控制台上打印一行来解释发生了什么并返回到方法的调用者。 (因此,在返回时,程序会认为loadData()
已完成并已返回。但是,它仍然会在没有向控制台或任何东西打印行的情况下崩溃抛出异常。这就像它完全忽略了我拥有的捕获到位。
CODE:
protected void loadData()
{
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
if(!saveFileObject.exists())
{
try
{
saveFileObject.createNewFile();
}
catch(IOException e)
{
System.out.println("Uh oh...");
e.printStackTrace();
}
}
// Create file input stream
try
{
fileIn = new FileInputStream(saveFileObject);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
// Create object input stream
try
{
inputStream = new ObjectInputStream(fileIn);
}
catch(IOException e)
{
e.printStackTrace();
}
// Try to deserialize
try
{
parts = (ArrayList<Part>)inputStream.readObject();
}
catch(EOFException e)
{
System.out.println("EOFException thrown! Attempting to recover!");
return;
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
// close input stream
try
{
inputStream.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
请帮忙吗?
答案 0 :(得分:0)
如何尝试一次,然后分别像here那样捕获?
答案 1 :(得分:0)
尝试编写代码,如:
protected void loadData() {
// Gets/creates file object.
saveFileObject = new File("savedata.ser");
try {
if (!saveFileObject.exists()) {
saveFileObject.createNewFile();
}
// Create file input stream
fileIn = new FileInputStream(saveFileObject);
// Create object input stream
inputStream = new ObjectInputStream(fileIn);
// Try to deserialize
parts = (ArrayList<Part>) inputStream.readObject();
// close input stream
inputStream.close();
} catch (EOFException e) {
System.out.println("EOFException thrown! Attempting to recover!");
} catch (IOException e) {
System.out.println("Uh oh...");
e.printStackTrace();
}
}
另请注意,EOFException
是IOException