0

This may be a dumb question, but I haven't been able to find the answer anywhere else. I have a class that will read and write to a file for saves. Now, I'm trying to handle some possible errors that could come my way. What I want to know is if this is legal or common practice in Java:

try {
    in = new ObjectInputStream(new FileInputStream(fileName));
    score = (Score)in.readObject();
} catch() {
    ...
}

The problem I'm having is if the file is empty, it cannot read the file. The program will crash, so I want to know is common or regular practice to create some data in the file from the catch statement, then try/catch it again. Then at the second catch I can crash the program.

The reason I have for wanting to do it this way is in the case that the user erases the data in the file.

If it's legal, would this be the syntax?

try {
    // try something here
} catch(//Exception here) {
    // Create a new file and try again.
    try {
        // try again
    } catch() {
        // Crash the program
    }
}
4

2 回答 2

1

Why don't you just check if the file doesn't exist or is empty before you try and use it?

try {
    File file = new File( fileName);
    if( !file.exists() || file.length() == 0) { 
        // Create the file, initialize it with some default value
    }
    in = new ObjectInputStream(new FileInputStream( file));
    score = (Score)in.readObject();
} catch() {
    ...
}

Note that there is a small race condition, where it is possible for the user to delete the file between when you check for the file's existence, and actually using it within the FileInputStream.

于 2013-04-10T02:35:36.937 回答
0

It's generally bad form to do work like this in a catch block. If you want to do a retry on failure, use a loop like

int retryCount = 0;
boolean success = false;
while(!success && retryCount < 2) {
    retryCount++;
    try {
        ...
        success = true;
    } catch (Exception ex) {
        // log exception
    }
}
于 2013-04-10T02:38:44.107 回答