gpt4 book ai didi

python - 在python中处理递归错误回溯

转载 作者:行者123 更新时间:2023-12-03 07:58:57 25 4
gpt4 key购买 nike

我正在努力在Python中实现小型编程语言,而该语言的执行基本上包括对名为execute的函数的递归调用。我已经实现了自己的错误处理,但是为了进行该错误处理,我需要捕获一些异常并将它们作为我自己的类型抛出,从而导致代码如下所示:

def execute(...):
try:
try:
# do stuff
except IndexError:
raise MyIndexError()
except MyErrorBase as e:
raise MyErrorBase(e, newTracebackLevel) # add traceback level for this depth

我真的很讨厌嵌套的 try块...有什么办法可以解决这个问题?

最佳答案

如果确实要执行此操作,请尝试在基本异常类型和新异常类型之间创建映射:

exceptionMap = {
IndexError: MyIndexError,
# ...
}

def execute(...):
try:
# do stuff
except tuple(exceptionMap) as e:
raise exceptionMap[type(e)](e, newTracebackLevel)

例:
In [33]: exceptionMap = {IndexError: RuntimeError}

In [34]: a = []

In [35]: try:
...: a[1]
...: except tuple(exceptionMap) as e:
...: raise exceptionMap[type(e)](str(e))

---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-35-bc6fdfc44fbe> in <module>()
2 a[1]
3 except tuple(exceptionMap) as e:
----> 4 raise exceptionMap[type(e)](str(e))
5
6

RuntimeError: list index out of range

关于python - 在python中处理递归错误回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39059859/

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