开发者

Try/Catch or IF for handling missing Files?

开发者 https://www.devze.com 2023-03-07 16:13 出处:网络
Is it better to try/catch exceptions or to use if statements to handle the different outcomes? I am writing a short program in Java to copy files for convenience, and use the ifs to handle the event

Is it better to try/catch exceptions or to use if statements to handle the different outcomes?

I am writing a short program in Java to copy files for convenience, and use the ifs to handle the event where a file does not exist, and declare the throws for each method, but don't use try/catch.

Should I go back and replace those ifs and the related sections with try/catches or is this "accepta开发者_运维百科ble" programming" for sharing with a small community of users?


If by missing, you mean the file should always be there, then that's an exception.

If you mean that a missing file is an ordinary (possible or even likely) occurance, then do not use an exception.


It's typically good design to check your inputs for validity (and deal with bad inputs) before passing them into a function. This usually results in easier to read and cleaner code.

However, the reality is that you're probably need to handle bad inputs in this case regardless of how much checking is done before you attempt the copy, and that's because even if you check that the file exists beforehand it could be deleted later, or another IO error could occur.


The only truly safe way to deal with missing files is to deal with the exception. Consider this:

if (file.exists() && file.canRead()) {
    try {
        is = new FileInputStream(file);
    } catch (IOException ex) {
        // Never happens
    }
}

In fact, the "never happens" case CAN happen. For example:

  • If file is actually a directory the open will fail. (You can deal with that by calling file.isDirectory(), but there are other cases that are hard to deal with ... like creating a file on a flakey removable medium.)

  • Suppose that some external application deletes the file or changes its permissions in the tiny window between this application testing the file and attempting to open it. There's simply no way to deal with this race condition ...

In addition, each of those tests is probably a system call. System calls are expensive - roughly as expensive as creating / throwing / catching an exception.

So, the best way to deal with the possibility of IO exceptions when opening a file is to LET THEM HAPPEN. By all means, use the File API to help diagnose the problem, but don't rely on it to avoid the IO exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号