Search code examples
pythonpython-3.xerror-handling

Logging and raising an exception


I'd like to keep a solid logging system going, but it's also necessary to raise exceptions. This code accomplishes what I'm going for, but it looks clunky and not very Pythonic. What's a better option?

import logging

if not condition_met:
    missing = set_one - set_two
    logging.error('Missing keys: {}'.format(missing))
    raise ValueError('Missing keys: {}'.format(missing))

Solution

  • you could catch the exception and log the error at this time, so if another exception occurs you can log it as well, and propagate the exception upstream.

    try:
       # some code
    
        if not condition_met:
            missing = set_one - set_two
            raise ValueError('Missing keys: {}'.format(missing))   
    
    except Exception as e:  # or ValueError to narrow it down
        logging.error(str(e))
        raise   # propagate the exception again
    

    note than logging an exception without logging the traceback leaves something unfinished, specially if the exception is caught and handled upstream. It's very likely that you're never going to fix that particular error.