bas*_*ibe 3 python exception-handling
我有一个要终止的循环KeyboardInterrupt:
while True:
try:
do_stuff()
except KeyboardInterrupt:
cleanup()
break
except Exception as e:
cleanup()
raise e
Run Code Online (Sandbox Code Playgroud)
这很好用,但是双重cleanup()对我来说似乎很不干净。我不喜欢重复的代码。我尝试使用上下文管理器代替,但是这引入了很多不必要的复杂性,并使文件大小几乎增加了一倍。
有没有更清晰的方式表达我的意图?
您可以使用BaseException她俩
try:
do_stuff():
except BaseException as e:
cleanup()
if isinstance(e, KeyboardInterruption):
break
raise e
Run Code Online (Sandbox Code Playgroud)
另外,您只能使用raise代替raise e
该finally关键字正是你所期待的。有关错误和异常的文档说明了其用法。
无论是否发生异常,始终在离开try语句之前执行finally子句
如果清理仅应在离开循环时进行,则建议交换循环并尝试:
try:
while True:
do_stuff()
except KeyboardInterrupt:
pass
finally:
cleanup()
Run Code Online (Sandbox Code Playgroud)