我正在编写一个与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
不存在,那么它们应该存在什么呢?
答案 0 :(得分:5)
现在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]
答案 1 :(得分:4)
我一发布就找到了在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
我曾考虑将此问题标记为欺骗,但考虑到其他相关问题都没有处理在此单一类型下区分不同异常的情况,我将此问题保留为解决这个问题并回答它。