user1427661
user1427661

Reputation: 11784

Defensive Programming or Wasted Time?

The general gist of this question: if there is even a remote possibility that something could go wrong, should I catch the possible error? Specifically:

I have an app that reads and writes the previous history of the program to a .txt file. Upon initialization, the program reads the history file to determine what operations it should and should not do. If no history file yet exists, it creates one. Like so:

global trackList
try:
    # Open history of downloaded MP3s and transfer it to trackList
    with open('trackData.txt', 'r') as f: 
        trackrackList = f.readlines()
except Exception, e: #if file does not exist, create a blank new one
    with open('trackData.txt', 'w') as f:
        f.write("")

The program then proceeds to download MP3s based on whether or not they were in the txt file. Once it has downloaded an MP3, it adds it to the txt file. Like so:

mp3File = requests.get(linkURL)
with open('trackData.txt', 'a') as f:
    f.write(linkURL + '\n')

Now, it is almost 100% percent certain that the txt file will remain since the time it was created in the first function. We're dealing with downloading a few MP3s here -- the program will never run for more than a few minutes. However, there is the remote possibility that the history txt file will have been deleted by the user or otherwise corrupted in while the MP3 was downloaded, in which case the program will crash because there is no error handling.

Would a good programmer wrap that last block of code in a try ... except block that creates the history txt file if it does not exist, or is that just needless paranoia and wasted space? It's trivial to implement, but keep in mind that I have programs like this where there are literally hundreds of opportunities for users to delete/corrupt a previously created txt file in a tiny window of time. My normally flat Python code would turn into a nested try ... except minefield.

Upvotes: 2

Views: 461

Answers (2)

phihag
phihag

Reputation: 288100

Why are you creating an empty file on application startup? Just do nothing if the file isn't present on startup - open('trackData.txt', 'a') will still create a new file.

Upvotes: 5

Knaģis
Knaģis

Reputation: 21485

A safer solution would be to open the file and keep it open while you are still downloading. The user will then not be able to delete it. After everything is downloaded and logged, close the file. This will also result in better performance.

Upvotes: 5

Related Questions