我知道这听起来很疯狂,但是我找不到解决方案。我试图使用break
在循环内排除try-except
语句。
这是我尝试过的:
for i in range(10):
try:
print(i)
break
except break:
print("Break excepted")
pass
但是
Python3.x
返回错误:SyntaxError: invalid syntax
那么,除了
break
语句之外,我该如何处理?附言:我知道我可以在
print
之前使用break
语句,而避免使用break
语句,但是如果我想这么做,我该怎么办?
最佳答案
您不能添加break
异常(exception),因为break
并非异常(exception)。
同样在操作流程中,如果循环无法运行,您的print(i)
将不会被执行,因此该代码无论如何都不会到达break语句。
如果您尝试查找代码在哪个循环处中断,那么您的代码也应该工作而无需中断。
for i in range(10):
try #try running the loop
print(i)
except: #if the loop breaks
print("Break excepted") #print this and continue loop
因为
try
在for循环内;当出现异常时,循环将继续下一次迭代。当然,您也可以捕获更特定的异常,例如
except IndexError
或except KeyError
。 The full list of exceptions is available in the documentation.
关于python - 除了Python中的中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61075202/