【问题标题】:Run some code if any exception occur and to a specific exception如果发生任何异常并针对特定异常运行一些代码
【发布时间】:2012-10-22 14:35:24
【问题描述】:

我有这个功能。我的 pygame 的文本到矩形转换器。

def text_to_rect(text, name='default'):
    try:
        font  = load.text_style[name]['font']
        aa    = load.text_style[name]['aa']
        color = load.text_style[name]['color']
    except NameError:
        font_path = pygame.font.get_default_font()
        font = pygame.font.Font(font_path, 24)
        aa = 1
        color = (0,0,0)
        if not name=='default':
            text = text+'(ERROR: Global load object not defined.)'
    except KeyError:
        font_path = pygame.font.get_default_font()
        font = pygame.font.Font(font_path, 24)
        aa = 1
        color = (0,0,0)
        if not name=='default':
            text = text+'(ERROR: '+name+' text style does not exist.)'
    return font.render(text,aa,color)

在两个 except 块中有 4 行相同的代码。如果发生任何异常,我想运行这 4 行,然后休息到特定的异常。

【问题讨论】:

  • 我不是 Python 或面向对象编程方面的专家,但您可能想看看多态性,并使其使某个错误扩展另一个错误。很抱歉我不能给出具体的例子,但是我记得我以前做Java的时候有这样的事情......

标签: python exception exception-handling python-2.7 pygame


【解决方案1】:

您实际上可以将异常合并到一个语句中:

try:
    #code that you expect errors from

except KeyError, NameError:
    #exception code

except:
    #Of course, you can also do a naked except to catch all
    #exceptions,
    #But if you're forced to do this, you're probably
    #doing something wrong. This is bad coding style.

编辑 对于您的情况,如果您希望代码执行依赖于捕获的错误,请执行以下操作:

try:
    #Code to try
except (KeyError, NameError) as e:
    #Code to execute in either case
    if isinstance(e, KeyError):
        #code to execute if error is KeyError
    else:
        #code to execute if error is NameError

【讨论】:

  • 好的。所以如果我得到 except KeyError, NameError: 块,如何检查发生了哪一个?
  • 在大约 neked 除外。以这种方式捕获异常并重新引发异常是一种好方法。 except:# do rollback or somthing# log that the exception occourraise
  • 在语义上与上述相同。但是,如果您要经常这样做,我会将上面的内容变成装饰器。
猜你喜欢
  • 1970-01-01
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多