How to prevent try catching every possible line in python?

前端 未结 6 1774
遥遥无期
遥遥无期 2020-12-14 02:42

I got many lines in a row which may throw an exception, but no matter what, it should still continue the next line. How to do this without individually try catching every si

6条回答
  •  被撕碎了的回忆
    2020-12-14 03:06

    I ran into something similar, and asked a question on SO here. The accepted answer handles logging, and watching for only a specific exception. I ended up with a modified version:

    class Suppressor:
        def __init__(self, exception_type, l=None):
            self._exception_type = exception_type
            self.logger = logging.getLogger('Suppressor')
            if l:
                self.l = l
            else:
                self.l = {}
        def __call__(self, expression):
            try:
                exec expression in self.l
            except self._exception_type as e:
                self.logger.debug('Suppressor: suppressed exception %s with content \'%s\'' % (type(self._exception_type), e))
    

    Usable like so:

    s = Suppressor(yourError, locals()) 
    s(cmdString)
    

    So you could set up a list of commands and use map with the suppressor to run across all of them.

提交回复
热议问题