Python:捕获任何异常并将其放入变量中

Mar*_*tin 5 python recursion exception

为了弄清楚要避免一些递归需要什么,我需要捕获任何异常(编辑:不只是从Exception派生的,但是所有异常,包括KeyboardInterrupt和用户异常),把它放在一个变量中,然后再重新提升它在捕获区外面.从本质上讲,我正试图推出自己的最终块.这可能吗?

实际问题是调用许多清理函数,如果其中任何一个失败,所有其他函数也应该被调用,那么失败的函数的异常仍然应该传播.这是我目前的解决方案,它需要一个Popen对象列表:

def cleanupProcs(procs):
    if not procs:
        return

    proc = procs.pop(0)
    try:
        proc.terminate()
        proc.wait()
    finally:
        cleanupProcs(procs)
Run Code Online (Sandbox Code Playgroud)

是否有迭代方法来做到这一点?更优雅的方式?一个更Pythonic的方式?

Tob*_*ler 7

如果你想要包含堆栈跟踪:

try:
    # something
except:
    the_type, the_value, the_traceback = sys.exc_info()
Run Code Online (Sandbox Code Playgroud)

后来

raise the_type, the_value, the_traceback
Run Code Online (Sandbox Code Playgroud)

(与此答案相关)

另请参见这里为Python 2.7.