本文介绍了简洁代码(初学者)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约30页(每页10 * 3页)这样的代码

(以下)。任何人都可以建议一种更简洁的方式来代码处理异常处理吗?如果有异常,我需要

继续循环,继续列表。


史蒂夫。


-----------------------------------

for devs devs

试试:

dev.read1()

除了

打印例外

删除开发者的开发者

开发者开发者的


尝试:

dev.read2()

除了

打印例外

从开发者中删除dev

开发者开发者的


尝试:

dev.read3()

除了

打印例外

从devs中移除dev



解决方案





for [''read1'',''read2'',''read3'']中的method_name:

对dev开发者来说:

试试:

meth = getattr(dev,method_name)

除了AttributeError,e:

#不应该发生,但我们想要处理它

your_code_here()

else:

试试:

meth()

除了(SomePossibleException,SomeOtherPossibleException),e:

打印e

#做什么需要删除dev from devs

#注意不要拧紧循环机械......


(剪辑)


I have about 30 pages (10 * 3 pages each) of code like this
(following). Can anyone suggest a more compact way to
code the exception handling? If there is an exception, I need
to continue the loop, and continue the list.

Steve.

-----------------------------------
for dev in devs
try:
dev.read1()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read2()
except
print exception
remove dev from devs

for dev in devs
try:
dev.read3()
except
print exception
remove dev from devs

etc.

解决方案

for method in (DevClass.read1, DevClass.read2, ...):
for dev in devs:
try:
method(dev)
except:
print execption
remove dev from devs

Diez




for method_name in [''read1'', ''read2'', ''read3'']:
for dev in devs:
try:
meth = getattr(dev, method_name)
except AttributeError, e:
# should not happen, but we want to handle it anyway
your_code_here()
else:
try:
meth()
except (SomePossibleException, SomeOtherPossibleException), e:
print e
# do what''s needed to remove dev from devs
# paying attention not to screw the looping machinery...

(snip)


这篇关于简洁代码(初学者)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 01:06