0

我有这个功能。我的 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 行,然后休息到特定的异常。

4

1 回答 1

6

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

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
于 2012-10-22T14:39:22.123 回答