Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: catch any exception and put it in a variable

To figure out what it would take to avoid some recursion, I need to catch any exception (edit: Not just ones derived from Exception, but all exceptions, including KeyboardInterrupt and user exceptions), put it in a variable, and later re-raise it outside the catch block. Essentially, I'm trying to roll my own finally block. Is this possible?

The actual problem is to call a number of cleanup functions, and if any of them fail, all the others should also be called, then the exception for the one that failed should still propagate. Here's my current solution, it takes a list of Popen objects:

def cleanupProcs(procs):
    if not procs:
        return

    proc = procs.pop(0)
    try:
        proc.terminate()
        proc.wait()
    finally:
        cleanupProcs(procs)

Is there an iterative way to do this? A more elegant way? A more Pythonic way?

like image 977
Martin C. Martin Avatar asked Oct 16 '13 14:10

Martin C. Martin


1 Answers

you can use:

procexceptions = []

except Exception, e:
    procexceptions.append(e)

and then later (after the loop for terminating processes) you can

raise procexceptions[0]

etc.

like image 147
Corley Brigman Avatar answered Sep 30 '22 12:09

Corley Brigman