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

后端 未结 6 1765
一整个雨季
一整个雨季 2020-12-14 06:06

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

try:
    funky code
finally:
    if ???:
          


        
6条回答
  •  悲哀的现实
    2020-12-14 06:48

    If it was me, I'd do a little re-ordering of your code.

    raised = False
    try:
        # funky code
    except HandleThis:
        # handle it
        raised = True
    except Exception as ex:
        # Don't Handle This 
        raise ex
    finally:
        if raised:
            logger.info('funky code was raised')
    

    I've placed the raised boolean assignment outside of the try statement to ensure scope and made the final except statement a general exception handler for exceptions that you don't want to handle.

    This style determines if your code failed. Another approach might me to determine when your code succeeds.

    success = False
    try:
        # funky code
        success = True
    except HandleThis:
        # handle it
        pass
    except Exception as ex:
        # Don't Handle This 
        raise ex
    finally:
        if success:
            logger.info('funky code was successful')
        else:
            logger.info('funky code was raised')
    

提交回复
热议问题