gpt4 book ai didi

python - 修改异常消息而不丢失引发堆栈

转载 作者:太空宇宙 更新时间:2023-11-03 21:22:54 26 4
gpt4 key购买 nike

我有一个 try/except 子句,它将返回或捕获 KeyError ,如下所示:

try:
return super().__new__(globals()[kls])
except KeyError:
raise

当使用不当时,这将生成堆栈跟踪,如下所示:

>>> g = Grid(cell='Circle')
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
g = Grid(cell='Circle')
File "<pyshell#1>", line 8, in __new__
return super().__new__(globals()[kls])
KeyError: 'SHPCircleGrid'
>>> g
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
g
NameError: name 'g' is not defined

这完全没问题,但是我想“扩展/修改”该消息以向用户解释如何再次避免此错误;即来自:

KeyError:'SHPCircleGrid'

KeyError:“SHPCircleGrid”。使用“Hex”、“Rect”或“Tri”作为单元格关键字。

同时为用户维护堆栈。捕获部分中的通用 print()g 设置为 NoneType 这是我不喜欢的,所以简单的打印并不是处理这个问题的方法。添加另一个 raise KeyError('some message') 会打印两个堆栈(“处理异常时另一个...”消息),这也是不需要的。

处理此问题的适当方法是什么,以便它可以扩展到类实例化可能引发 KeyError 的任何其他关键字?

最佳答案

难道您不能通过向 KeyError 提供消息来实现这一点吗:

try:
return super().__new__(globals()[kls])
except KeyError as e:
key = "'{}'".format(*e.args)
base = "{}. Use 'Hex', 'Rect' or 'Tri' for cell keyword."
raise KeyError(base.format(key)) from None

关于python - 修改异常消息而不丢失引发堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54101639/

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