【问题标题】:Catch same exception multiple times [duplicate]多次捕获相同的异常[重复]
【发布时间】:2017-07-11 15:28:49
【问题描述】:

如果引发异常,有什么方法可以继续执行try 块?我认为答案是否定的,但我认为下面的代码很难看。

def preprocess(self, text):
    try:
        text = self.parser(text)
    except AttributeError:
        pass
    try:
        terms = [term for term in text if term not in self.stopwords]
        text = list_to_string(terms)
    except AttributeError:
        pass
    try:
        terms = [self.stemmer.stem(term) for term in text]
        text = list_to_string(terms)
    except AttributeError:
        pass
    return text

还有另一种以 Python 形式执行此操作的方法吗?

【问题讨论】:

  • 可以使用finally关键字errors in python
  • 是的,但是如果这样做会有很多嵌套代码
  • 为什么所有语句都不在一个try 部分?
  • @omri_saadon:是的,但问题是您不知道try 停止的位置以及继续的位置。唯一的解决方案是用 try... 包围每个语句
  • 也许与 contextlib:from contextlib import suppress with suppress(AttributeError):

标签: python python-3.x


【解决方案1】:

我会这样重写:

def preprocess(self, text):
    if hasattr(self, 'parser'): 
        text = self.parser(text)

    if hasattr(self, 'stopwords'): 
        terms = [term for term in text if term not in self.stopwords]
        text = list_to_string(terms)

    if hasattr(self, 'stemmer'):        
        terms = [self.stemmer.stem(term) for term in text]
        text = list_to_string(terms)

    return text

我认为它更容易理解并且不会在 parserstem 调用中捕获 AttributeError

【讨论】:

  • 是的,如果可能,最好避免异常。 +1 跳出这个重复问题的框框思考。
猜你喜欢
  • 1970-01-01
  • 2016-05-28
  • 2010-09-13
  • 2014-07-09
  • 2012-07-13
  • 2011-12-07
  • 2013-01-31
  • 2021-09-09
  • 2015-02-19
相关资源
最近更新 更多