Try / catch or IF to handle missing files?

Are you better off trying / catching exceptions or using if statements to handle different results?

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

Should I go back and replace these ifs and related sections with try / catch or is this "acceptable" programming "to be shared with a small community of users?

+4
source share
3 answers

If absent, you mean that the file should always be there, and then an exception.

If you mean that the missing file is a normal (possible or even probable) event, then do not use an exception.

+5
source

This is usually a good design to check your inputs for validity (and deal with bad inputs) before passing them to a function. This usually results in easier reading and cleaner code.

However, the reality is that you will probably have to handle bad entries in this case, no matter how many checks are performed before trying to copy, and this is because even if you check that the file exists in advance, you can delete it later or another I / O error may occur.

+3
source

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

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

In fact, the “never happens” CAN case may occur. For instance:

  • If file is actually a directory, then open will fail. (You can handle this by calling file.isDirectory() , but there are other cases that are difficult to handle ... for example, creating a file on removable removable media.)

  • Suppose an external application deletes a file or changes its permissions in a tiny window between this application that checks the file and tries to open it. There is simply no way to deal with this race condition ...

In addition, each of these tests is probably a system call. System calls are expensive - about as expensive as creating / throwing / catching exceptions.

Thus, the best way to deal with the possibility of IO exceptions when opening a file is to YEAR THEM FOR YEARS. By all means, use the API file to help diagnose the problem, but don't rely on it to avoid an IO exception.

+2
source

All Articles