简体   繁体   中英

Handling exceptions in the catch block?

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
    }
}

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 .

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM