简体   繁体   English

处理python中的递归错误回溯

[英]Handling recursive error tracebacks in python

I'm working on implementing a small programming languge in Python for the hell of it, and the language's execution basically consists of recursive calls to a function called execute . 我正在努力在Python中实现一个小编程语言,而语言的执行基本上包括对一个名为execute的函数的递归调用。 I've implemented my own error handling, but in order to have that error handling work I need to catch some exceptions and throw them as my own types, resulting in code that looks something like this: 我已经实现了自己的错误处理,但为了让错误处理工作,我需要捕获一些异常并将它们作为我自己的类型抛出,导致代码看起来像这样:

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

I really hate the nested try blocks... is there any way to fix this? 我真的很讨厌嵌套的try块......有什么方法可以解决这个问题吗?

You need to set try statements when ever needed. 您需要在需要时设置try语句。

Put it only on start of execution. 把它放在执行开始时。

try statement is basically is a longjump. try语句基本上是一个longjump。 You want to do some long tasks which may fail at any place in the code it can be in inner calls. 您希望执行一些长任务,这些任务可能会在内部调用中的代码中的任何位置失败。 longjump helps you to catch fails. longjump帮助你捕获失败。

In lua language there's method called pcall. 在lua语言中有一种叫做pcall的方法。 (protected call) Whenever it invokes at error the call returns error status and error message is taken as the second return value. (受保护的调用)每当它调用错误时,调用返回错误状态,并将错误消息作为第二个返回值。

If you really want to do this, try creating a mapping between base exception types and your new exception types: 如果您确实想这样做,请尝试在基本异常类型和新的异常类型之间创建映射:

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

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

Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM