pythonexceptionloggingcontrol-flowtry-finally

How to determine if an exception was raised once you're in the finally block?


Is it possible to tell if there was an exception once you're in the finally clause? Something like:

try:
    funky code
finally:
    if ???:
        print('the funky code raised')

I'm looking to make something like this more DRY:

try:
    funky code
except HandleThis:
    # handle it
    raised = True
except DontHandleThis:
    raised = True
    raise
else:
    raised = False
finally:
    logger.info('funky code raised %s', raised)

I don't like that it requires to catch an exception, which you don't intend to handle, just to set a flag.


Since some comments are asking for less "M" in the MCVE, here is some more background on the use-case. The actual problem is about escalation of logging levels.

Hence, the code runs under a log capture context (which sets up custom handlers to intercept log records) and some debug info gets re-logged retrospectively:

try:
    with LogCapture() as log:
        funky_code()  # <-- third party badness
finally:
    # log events are buffered in memory. if there was an exception,
    # emit everything that was captured at a WARNING level
    for record in log.captured:
        if <there was an exception>:
            log_fn = mylogger.warning
        else:
            log_fn = getattr(mylogger, record.levelname.lower())
        log_fn(record.msg, record.args)

Solution

  • raised = True
    try:
        funky code
        raised = False
    except HandleThis:
        # handle it
    finally:
        logger.info('funky code raised %s', raised)
    

    Given the additional background information added to the question about selecting a log level, this seems very easily adapted to the intended use-case:

    mylog = WARNING
    try:
        funky code
        mylog = DEBUG
    except HandleThis:
        # handle it
    finally:
        mylog(...)