Python:虽然不是异常

新手上路,请多包涵

所以我知道您可以使用 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 AttributeErrorwhile not AttributeError() ,它们都完全跳过了 while 块中的任何内容。那么,有没有办法在 Python 中做到这一点?

编辑: 这本身并不是一个 _循环_,但是 while 块会运行,如果遇到错误则继续运行,如果到达末尾则继续运行。

原文由 miike3459 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 648
2 个回答

你能试试这样的东西吗:

 while True:
    try:
        print("ok")
        print(str.translate)
        print(str.foo)
    except:
        break
print('done')

原文由 Lucas Resende 发布,翻译遵循 CC BY-SA 4.0 许可协议

以下代码将循环直到遇到错误。

 while True:
  try:
    print("ok")
    print(str.translate)
    print(str.foo)
  except AttributeError:
    print("oops, found an error")
    break
  print("done")

原文由 Ghorich 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题