1

In the case of exceptions, I want the program to catch them, log them, then move on to the next iteration. Obviously a KeyboardInterrupt should still be raised so that the program can be stopped, but are there any other exceptions I should raise?

Very rough example of code below. This is a decorator which catches exceptions and logs them. Basically, should I have any other except cases?

def exception_logger(func):

    @wraps(func)
    def wrapper(*args, **kwargs):

        # Run as normal
        try:
            return func(*args, **kwargs)
        except KeyboardInterrupt:
            raise

        # Any other exception that occurs is logged
        except:
            log_file = 'example.txt'
            logger = logger_format(log_file)

            logger.exception(f'\nAn exception occurred with: {func.__qualname__}\n')
            print(f'\n\nAn exception occurred with: {func.__qualname__}\nView the log file for details.\n'.upper())

    return wrapper


Thanks.

QuantumChris
  • 963
  • 10
  • 21

1 Answers1

1

Instead of a blacklist (that might age poorly), you should just be catching Exception instead of using except:. It excludes KeyboardInterrupt and various others you shouldn’t suppress. (It might be OK to log them, but you don’t seem to want to do that anyway.) See also advice against except: pass in particular for context.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76