Python: catch any exception and put it in a variable

To find out what is needed to avoid some recursion, I need to catch any exception (change: not only those that are received from Exception, but all exceptions, including KeyboardInterrupt and user exceptions), put it in a variable and later raise it outside catch block. Essentially, I'm trying to collapse my own block. Is it possible?

The real problem is calling several cleanup functions, and if any of them fails, all the others should be called as well, then the exception for the one that failed should continue. Here is 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? More elegant way? More pythonic way?

+4
7

:

try:
    # something
except:
    the_type, the_value, the_traceback = sys.exc_info()

raise the_type, the_value, the_traceback

( )

. Python 2.7.

+7

, , , .

bum bum baaaaa . , , - - (, ) .

, , , . , . , . :

import logging
log = logging

def get_some_cheese():
    raise ValueError("Sorry, we're right out.")

try:
    get_some_cheese()
except:
    log.exception("What a waste of life")

, . , , , , , - , stdout/err, . , , - , , , .

+2
0

Python, . , , :

>>> def to_int(x):
...     try:
...         return int(x)
...     except Exception, e:
...         print 'in exception block:', e
...     print 'after exception block:', e

>>> to_int('12')
12
>>> to_int('abc')
in exception block: invalid literal for int() with base 10: 'abc'
after exception block: invalid literal for int() with base 10: 'abc'
0

:

procexceptions = []

except Exception, e:
    procexceptions.append(e)

( )

raise procexceptions[0]

...

0

:

>>> try:
...     #something
... except BaseException, e: # OK. Using BaseException instead of Exception
...     pass
... 
>>> 
>>> raise e
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> 
0

, , BaseException, , , ( ). , (re-raise, log ..), , .

def runCleanup(procs):
    exceptions = []
    for proc in procs:
        try:
            proc.terminate()
            proc.wait()
        except BaseException as e:
            exceptions.append(e) # Use sys.exc_info() for more detail

    return exceptions # To be handled or re-raised as needed
0

All Articles