![](/img/trans.png)
[英]Is there a way in python to execute a piece of code only if any exception is raised in a try/except block?
[英]In python, is there a way to enter a try/except block if a condition is met, otherwise execute the code in the try block plainly?
我想执行一个尝试运行代码块的循环,并跳过任何碰巧失败的迭代。 但是,我也希望能够传入一个调试标志,这样如果其中一个迭代失败,程序就会崩溃,用户可以查看回溯以帮助自己查看失败的位置。 基本上,我想这样做:
debug = False # or True
for i in range(10):
if not debug:
try:
# many lines of code
except:
print(f'Case {i} failed')
else:
# many lines of code
但是,我不想重复#many lines of code
。 我可以将它们包装在一个辅助函数中并精确地执行我上面写的结构,但是我将不得不传递一堆会增加一些复杂性的变量(也就是我不想编写的单元测试)。 有没有另一种方法可以做到这一点?
避免将many lines of code
分解为自己的函数(这通常是一个好主意,但并非总是如此)的最佳解决方案是无条件使用try
/ except
,但让except
有条件地重新引发异常:
debug = False # or True
for i in range(10):
try:
# many lines of code
except:
if debug:
raise # Bare raise reraises the exception as if it was never caught
print(f'Case {i} failed')
一个捕获的异常被一个空的raise
没有留下用户可见的痕迹来区分它与未捕获的异常; 回溯没有变化,没有任何迹象表明它通过了except
块,因此净效果与您的原始代码相同,除了稍后评估debug
(如果没有异常发生,则根本不会)和many lines of code
只出现一次.
旁注: except
块except
裸露是一个坏主意。 如果不出意外,请将其限制为except Exception:
这样您就不会在非调试模式下捕获和抑制诸如KeyboardInterrupt
或SystemExit
类的东西。
最好的方法是使用一个函数,多一行也无所谓。
否则,如果不需要测试debug
,则不需要重复else
块。 因为如果try
语句不会引发错误,那么它将执行并且结果将正常显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.