如何单独捕获这些异常?
我正在写一个Python程序,用来和Quickbooks(一个财务软件)进行交互。在连接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
这两个错误并不存在,那我应该用什么来替代它们呢?
3 个回答
我想在这里补充一点,关于@jizhihaoSAMA的回答,这是基于@dotancohen的回答,希望能让大家更清楚一些。
当你在捕捉特定的BaseException时,可能还想处理一些你没有预料到的其他错误。如果不这样做,代码可能会执行完毕,但结果却不是你所期望的。
except BaseException as e: # to catch pywintypes.error
if e.args[0] == -2147352567:
print(my_str)
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]
。
我一发帖就找到了一个方法,可以以非通用的方式捕捉异常,这个方法是在一个相关问题的侧边栏里看到的。下面是捕捉这些异常的方法:
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
我曾考虑把这个问题标记为重复,但考虑到其他相关问题都没有处理在这种单一类型下区分不同异常的情况,我决定保留这个问题,因为它解决了这个问题并给出了答案。