所以我知道您可以使用 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 块会运行,如果遇到错误则继续运行,如果到达末尾则继续运行。
原文由 miike3459 发布,翻译遵循 CC BY-SA 4.0 许可协议
你能试试这样的东西吗: