gpt4 book ai didi

python - 如何单独捕获这些异常?

转载 作者:太空狗 更新时间:2023-10-30 02:45:20 28 4
gpt4 key购买 nike

我正在编写一个与 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!')

当然,异常(exception)QbWrongModeErrorQbClosedError不存在,那么应该有什么来代替它们呢?

最佳答案

一发布,我就找到了在 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

我曾考虑过将这个问题标记为一个骗局,但考虑到其他相关问题都没有处理在这种单一类型下区分抛出的不同异常的情况,我把这个留作原样处理并回答这个问题。

关于python - 如何单独捕获这些异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25053785/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com