我正在编写一个与Quickbooks接口的Python程序。连接到Quickbooks时,根据问题,我可能会遇到以下两种常见异常之一:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'QBXMLRP2.RequestProcessor.2', 'The QuickBooks company data file is currently open in a mode other than the one specified by your application.', None, 0, -2147220464), None)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'QBXMLRP2.RequestProcessor.2', 'Could not start QuickBooks.', None, 0, -2147220472), None)
[使用except Exception as e
捕获通用异常表明e
的类型为<class 'pywintypes.com_error'>
,不能用于捕获异常:
... catch pywintypes.com_error as e:
NameError: global name 'pywintypes' is not defined
所以我怎么能以非通用的方式捕获这两个异常?理想情况下,代码应具有以下布局:
try:
qb = qbsdk_interface.Qbsdk_Interface(QB_FILE)
except QbWrongModeError as e:
print('Quickbooks is open in the wrong mode!')
except QbClosedError as e:
print('Quickbooks is closed!')
except Exception as e:
print('Something else went wrong!')
当然,例外QbWrongModeError
和QbClosedError
不存在,所以应该在什么地方出现?
我发布帖子后,立即发现了一种以非通用方式在question that appeared in the Related sidebar中捕获异常的方法。这是捕获这些异常的方法:
from pywintypes import com_error
except com_error as e:
请注意,无法单独处理导致异常的不同原因,因此必须通过比较except
的值在e.exceptinfo[5]
子句中检查返回码:
except com_error as e:
if e.excepinfo[5] == -2147220464:
print('Please change the Quickbooks mode to Multi-user Mode.')
elif e.excepinfo[5] == -2147220472:
print('Please start Quickbooks.')
else:
raise e
我曾考虑将此问题标记为重复,但考虑到其他相关问题均未解决在这种单一类型下抛出的不同异常之间的区别的情况,我将其保留为该问题,并回答。
现在pywintypes.error
是BaseException
。
不需要from pywintypes import com_error
。
如果您想捕获此异常。你可以赶上BaseException
except BaseException as e: # to catch pywintypes.error
print(e.args)
例外的格式如下:
(0, 'SetForegroundWindow', 'No error message is available')
因此,如果要检查返回码,请使用e.args[0]
而不是e.exceptinfo[5]