Keep trying

Yesterday I remembered a problem that I had with the following try/except block.

zfile = zipfile.ZipFile(sfile)
print("Problem with %s" %sfile)

With this code the original error messages were supressed and there was no way I could tell what exactly went wrong. If the file is missing or if it is not a valid zip file the error message would be the same.
The problem was that I used the except without specifying the error I am trying to catch.

A somewhat better code would be:

zfile = zipfile.ZipFile(sfile)
except IOError:
print("File %s does not exist" %sfile)
except zipfile.BadZipfile:
print("File %s is not a zip file" %sfile)

The casing of zipfile.BadZipfile was not obvious and I did struggle with it.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s