在下面,我有一个try-except块,我想重构它。如您所见,它不是Python式的,并且不可维护。在
try:
try:
foo()
except xError:
doSth()
raise
except:
exc_type = sys.exc_info()[0]
if exc_type == FooError:
doBlaBla()
else:
doFlaFla()
blablabla() # whatever the exceptions is, run this code block
foobar()
zoo()
...
我将该块更改为下面的代码
^{pr2}$如你所见,我需要一个除了最后的类操作。它不会在没有异常但引发任何异常时运行。你有什么建议?我该怎么换这个土块?在
你为什么要用免责块? 在我看来,一个好的做法是把最后一个例外陈述,这样会捕捉到意想不到的错误。在
所以我建议:
可以将异常代码包装在try finally块中,例如:
另一种方法可以是这样的:
^{pr2}$为什么不是这样的:
然后将其分解成一个
^{pr2}$try
:空的
except
是usually a bad idea。在相关问题 更多 >
编程相关推荐