【发布时间】:2017-04-17 14:55:58
【问题描述】:
我有以下功能:
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
根据驱动器状态,可能会发生此错误,我希望我的异常捕获特定错误:
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.')
使用type(exception).__name__,将错误重新发布为错误类型。这似乎与 Python 错误类型的典型格式不同,如果我使用
except error:
为了捕捉它,我得到了这个异常:
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
那么为什么这不能像我预期的那样工作,我如何在没有通用异常的情况下捕获这个异常?
【问题讨论】:
-
你的意思可能是:
except Exception as error:,除非你在某处定义了error。 -
很奇怪。看看
type(exception).__module__。 -
你的错误不是
win32api.error吗? -
@user2357112 返回“pywintypes”,但也无法解决。
标签: python python-2.7 exception-handling