在下面,我有一个try-except块,我想重构它。如你所见,它不是pythonic而且不可维护。
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()
...
我将该块更改为以下代码;
try:
try:
foo()
except xError:
doSth()
raise
except FooError:
doBlaBla()
raise
except:
doFlaFla()
raise
blablabla() # This is where the problem happens for me.
foobar()
zoo()
...
正如您所看到的,我需要一个除了 - 最后之类的操作。当没有异常引发但任何异常时它都不会运行。你有什么建议?我应该如何更改这个clode块?
答案 0 :(得分:0)
为什么你曾经使用过一次尝试免除块? 在我看来,最好把除了语句之外的东西放在一起,这会抓住意想不到的错误。
所以我建议:
try:
fn()
except Exception1:
do stuff you want
except Exception 2:
do another stuff
except Exception as e:
# Here you will catch an unexpected error, and you can log it
raise UnknownError -> do stuff you want
答案 1 :(得分:0)
您可以将您的异常代码包装在try-finally块中,例如:
try:
try:
foo()
except xError:
doSth()
raise
# catch Exception to avoid catching system errors
except Exception as e:
try:
if isinstance(e, FooError):
doBlaBla()
else:
doFlaFla()
raise
finally:
# this will always run regardless of what you raise
另一种方法可能是这样的:
e = None
try:
try:
foo()
except xError:
doSth()
raise
except FooError as e:
doBlaBla()
except Exception as e:
doFlaFla()
raise
finally:
# this will always run regardless of what you raise
if e:
# exception took place...
答案 2 :(得分:0)
为什么不能这样:
def others():
"""Other stuff to do when non-xError occurs."""
blablabla()
foobar()
zoo()
然后将因子分解为单个try
:
try:
foo()
except xError:
doSth()
raise
except FooError:
doBlaBla()
others()
except Exception:
doFlaFla()
others()
裸except
是usually a bad idea。