1

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?

PhilippNagel
  • 70
  • 1
  • 15

1 Answers1

1

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
Taku
  • 31,927
  • 11
  • 74
  • 85
  • Thanks. I don't work with win32api much. This does not seem intuitive to me, is it typical of other packages, or a win32api'ism? – PhilippNagel Apr 17 '17 at 15:14
  • Generally, most library/package/module has some sort of a "base" exception class which is a subclass of Exception, and it have multiple subclasses under that, handling more specific errors, usually the "base" exception class is ever raised directly, but this does sometimes happen when the developer doesn't want to create a unique subclass for every type of exceptions possible. – Taku Apr 17 '17 at 15:19