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)

2 つのexceptブロックには、同じコードが 4 行あります。例外が発生した場合はこれらの 4 行を実行し、特定の例外まで残ります。

4

1 に答える 1

6

実際には、例外を 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
于 2012-10-22T14:39:22.123 に答える