Jens
Jens

Reputation: 6375

Loading a file: Check existence or catch exception

In a project I need to load a file from the harddisc for further processing. I wrote code that first checks if the filename exists and then loads the file.

However, when thinking further about it I asked myself if that is at all clever. You don't block the file by the existence check so it is (while unlikely) possible that the file is deleted between you checking if it exists and you actually loading it.

The other idea is to just wrap the loading in a (in my case) Try + Except block and ditch the existence check alltogether. However I read that using exceptions for actual code flow is bad practice.

Should I use the first, the second or both methods, with the exception handling as a fallback?

Upvotes: 1

Views: 221

Answers (2)

MSDN has a note about this very issue:

Be aware that another process can potentially do something with the file in between the time you call the Exists method and perform another operation on the file, such as Delete.

It certainly doesn't hurt to check if a file exists first and handle the situation elegantly when it can be easily detected. Then, a Try/Catch for the truly exceptional situations (ie your fallback).

The "bad practice" rap depends on how it is used. In the situation you describe, it sounds like the Try/Catch would be caught and handled in one procedure. Thats not really controlling code flow, but using it as intended.

If you were to catch the exception, translate it and throw your own exception for an encapsulating object to catch (Foo.Bar.DoSomething Throws for Foo to Catch), that would be bad - almost like a NET version of spaghetti code. It could also affect performance.

Upvotes: 1

JP Veldtman
JP Veldtman

Reputation: 182

You will always check if the file exists, and preferably permissions before you do anything to the file (Edit, delete, move etc) - depending on what exactly you want to do and what type of file it is. But when you actually want to make a change to the file you will have to add to a Try Block. For example if you want to access a file on a flash drive and the flash drive is unplugged. you can't predict that

Upvotes: 1

Related Questions