【发布时间】:2019-05-27 01:11:26
【问题描述】:
所以我知道您可以使用try/except 块来操纵错误的输出,如下所示:
try:
print("ok")
print(str.translate)
print(str.foo)
except AttributeError:
print("oops, found an error")
print("done")
...给出以下输出:
ok
<method 'translate' of 'str' objects>
oops, found an error
done
现在,有没有办法使用while 循环执行以下操作,例如while not AttributeError,如下所示:
while not AttributeError:
print("ok")
print(str.translate)
print(str.foo)
print("done")
如果没有oops, found an error,它会给出与上面相同的输出?这将减少对 except: pass 类型块的需求,如果您在 except 块中无事可做,这是必要的,但有点毫无意义。
我尝试了while not AttributeError 和while not AttributeError(),它们都完全跳过了while 块中的任何内容。那么,有没有办法在 Python 中做到这一点?
编辑:这真的不是一个 循环 本身,但是 while 块会运行,如果遇到错误则继续,如果遇到错误则继续它到达了终点。
【问题讨论】:
-
您必须将
try/except块视为“如果一切正常”/“else”。 Python 引发所有错误,如果你想“跳过”一个,except AttributeError: pass是要走的路。这不是毫无意义的,您明确表示您想让这个错误通过(或应用另一个进程,或其他)。编辑:而且,没有while not AttributeError -
如果没有引发异常,会重复吗?
-
@DavisHerring 不,它将运行该块直到结束,并且无论是否有错误,它都会继续运行。如果出现错误,它会提前结束并继续。
-
这是一个无限循环吗?停止条件是什么?遇到异常会中断吗?
-
这不是应使用异常的方式 - 请使用标准的
try/except方法。
标签: python python-3.x exception while-loop