PhilippNagel
PhilippNagel

Reputation: 70

Unable to catch "error" type exception

I have the following function:

def findHardDriveLetter(drivename):
    drives = win32api.GetLogicalDriveStrings()
    drives = drives.split('\000')[:-1]
    for drive in drives:
        try:
            volname = win32api.GetVolumeInformation(drive)[0].upper()
        except:
            pass
        if volname == drivename.upper():
            return drive

Depending on drive state, this error can occur, and I would like my except to catch the specific error:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "<editor selection>", line 5, in findHardDriveLetter
error: (21, 'GetVolumeInformation', 'The device is not ready.')

Using type(exception).__name__, the error is reposted to be of type error. This seems to be different from the typical format of Python error types, and if I use

except error:

to catch it, I get this exception:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "<editor selection>", line 20, in findHardDriveLetter
NameError: global name 'error' is not defined

So why is this not working as I expect, and how do I catch this exception without a generic except?

Upvotes: 1

Views: 1330

Answers (1)

Taku
Taku

Reputation: 33704

You can except win32api.error since this is the exception type you been getting, but it's generally used as the base class of all win32api exceptions...weird

try:
    # ....
 except win32api.error:
    pass

Upvotes: 1

Related Questions