tripl3dogdare tripl3dogdare - 3 months ago 7
Python Question

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

. 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(...):
# 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
blocks... is there any way to fix this?


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(...):
        # 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))

RuntimeError: list index out of range