ava*_*chy -2 python pygame exception-handling exception python-2.7
我有这个功能.我的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)
Run Code Online (Sandbox Code Playgroud)
在两个除了块之外,有4行相同的代码.如果发生任何异常,我想运行这4行,然后休息到特定的异常.
您实际上可以将异常组合到一个语句中:
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.
Run Code Online (Sandbox Code Playgroud)
编辑 对于您的情况,如果您希望代码执行依赖于捕获的错误,请执行以下操作:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1576 次 |
| 最近记录: |