首页 / PYTHON / Python异常控制/流问题
Python异常控制/流问题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python异常控制/流问题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1777字,纯文字阅读大概需要3分钟。
内容图文
![Python异常控制/流问题](/upload/InfoBanner/zyjiaocheng/730/4851a65100e94ed1b4511edfb3f42181.jpg)
我一直在使用Python并遇到了一些必须经常发生的事情.
我有五个陈述都属于提高的常见陷阱
FooException和BarException.我想运行它们,防范它们
这些异常但即使在之后引发异常也会继续处理
一些处理完成.现在,我可以这样做:
try:
foo()
except (FooException, BarException):
pass
try:
bar()
except (FooException, BarException):
pass
try:
baz()
except (FooException, BarException):
pass
try:
spam()
except (FooException, BarException):
pass
try:
eggs()
except (FooException, BarException):
pass
但这真的很冗长,极端违反DRY.相当蛮力
明显的解决方案是这样的:
def wish_i_had_macros_for_this(statements, exceptions, gd, ld):
""" execute statements inside try/except handling exceptions with gd and ld
as global dictionary and local dictionary
statements is a list of strings to be executed as statements
exceptions is a list of strings that resolve to Exceptions
gd is a globals() context dictionary
ld is a locals() context dictionary
a list containing None or an Exception if an exception that wasn't
guarded against was raised during execution of the statement for each
statement is returned
"""
s = """
try:
$STATEMENT
except (%s):
pass
""" % ','.join(exceptions)
t = string.Template(s)
code = [t.substitute({'STATEMENT': s}) for s in statements]
elist = list()
for c in code:
try:
exec c in gd, ld
elist.append(None)
except Exception, e:
elist.append(e)
return elist
使用顺序如下:
>>> results = wish_i_had_macros_for_this(
['foo()','bar()','baz','spam()','eggs()'],
['FooException','BarException'],
globals(),
locals())
[None,None,None,SpamException,None]
有没有更好的办法?
解决方法:
那这个呢?
#!/usr/bin/env python
def foo():
print "foo"
def bar():
print "bar"
def baz():
print "baz"
for f in [foo, bar, baz]:
try:
f()
except (FooException, BarException):
pass
内容总结
以上是互联网集市为您收集整理的Python异常控制/流问题全部内容,希望文章能够帮你解决Python异常控制/流问题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。