我有这个功能。我的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)
在两个除块之外,有4行相同的代码。如果发生任何异常,我想运行这4行,然后休息到特定的异常。
答案 0 :(得分: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