Python中的嵌套try-except块可以简化吗?
大家好,我的Python代码大概是这样的:
try:
foo1()
except FooError1:
try:
foo2()
except FooError2:
dosth()
raise raisesth()
我想知道在Python中是否支持在try-except语句中使用多个条件或者复合条件,这样我的代码就可以简化成:
try:
foo1()
foo2()
except FooError1 and FooError2:
dosth()
raise raisesth()
谢谢!
2 个回答
1
异常 和 ;-).
def foo1():
return 1/0
def foo2():
return s
def do_something():
print("Yes!")
def exception_and(functions, exceptions, do_something):
try:
functions[0]()
except exceptions[0]:
if len(functions) == 1:
do_something()
else:
exception_and(functions[1:], exceptions[1:], do_something)
# ================================================================
exception_and([foo1, foo2], [ZeroDivisionError, NameError], do_something)
# Behaves the same as:
try:
foo1()
except ZeroDivisionError:
try:
foo2()
except NameError:
do_something()
1
我建议你去看看Python的官方文档。
我猜你是想在foo1()
或foo2()
出现错误时,调用dosth
来处理这些错误,就像你第二个代码块里那样。
try:
foo1()
foo2()
except (FooError1, FooError2):
dosth()
raise raisesth()
需要提醒你的是,在except
语句中可以使用and
条件,但一旦出现错误,必须立即处理这个错误,否则程序会停止运行。所以你不能让解释器等着FooError2
出现再去处理...