我有代码。我用
print(a)
表示错误。错误开始无休止地打印。我希望抛出异常时打印错误代码,但代码从导致错误的行之后的下一行继续执行
while True:
try:
print(a)
except Exception as e:
print(e)
continue
但是代码会从有错误的行重新开始,需要忽略行并继续。
输出: 没有找到a 没有找到a ...
我会描述我想要的:
try:
print(a) #Line of code 1
except:
pass
try:
print(b) #Line of code 2
except:
pass
我想检查像这样的所有代码行是否有错误
但是我的代码有 200 多行,这么多 try- except 结构做起来很愚蠢,不是吗
您应该将
continue
更改为 break
。
while True:
try:
print(a)
except Exception as e:
print(e)
break
您可以阅读更多循环控制语句 这里。
如果您想在同一个循环中运行,没有任何 continue 块,您只需添加其余代码,因为它位于 try 和 except 块之外,如下所示:
while (condition):
try:
print(a)
except Exception as e:
print(e)
# followed by the rest of code
print("contd")
或者如果您想跳过当前循环,可以使用
continue
。
之所以会重复这个过程,是因为您已将循环条件设置为 true,因此循环永远不会结束。要停止循环,您将需要一个
break
语句而不是 continue。