Chris Aung
Chris Aung

Reputation: 9492

Python error exception

I have a script which create a temporary text file and delete after the user close the window.

The problem is that, the temporary text file may or may not be created depending on what the user does.Or sometimes the temporary text file may be deleted before the user exit. There are three possible scenario.

  1. The temporary text file is created with the name of 'tempfilename'.
  2. The temporary text file is created with the name of 'tempfilename' but deleted before the user exit.So, when trying to remove the file it raise OSError
  3. The temporary text file is not created and no variable called 'tempfilename' is created, so it raise NameError

I have tried using this code:

try:
    os.remove(str(tempfilename))
except OSError or NameError:
    pass

But it seems that it only catch the OSError only. Did i do something wrong?

Upvotes: 0

Views: 180

Answers (2)

Alex Quinn
Alex Quinn

Reputation: 4213

tempfilename = None

# ...

if tempfilename is not None and os.path.exists(tempfilename):
    os.remove(tempfilename)

It's not good to catch NameError since it will hide other typos in your code (e.g., os.remov(…)).

Also, OSError does not always means that the file did not exist. On Windows, if the file was in use, an exception would be raised (http://docs.python.org/2/library/os.html#os.remove). In that case, you would want to see the exception so you could be aware of the issue and/or handle it another way.

Exception handlers should be kep as narrow as possible to avoid hiding unrelated errors or bugs

Upvotes: 0

zhangyangyu
zhangyangyu

Reputation: 8610

try:
    os.remove(str(tempfilename))
except (OSError, NameError):
    pass

Upvotes: 3

Related Questions