如果出现任何错误,是否可以在循环中运行try语句?

2024-10-03 04:32:22 发布

您现在位置:Python中文网/ 问答频道 /正文

如果出现错误,那么它将转到except语句之后的try语句,程序将在那里结束。我的问题是,如果出现错误而程序没有结束,它是否会连续运行try语句

例如:

try:
    some error caught
except:
    go to try statement again

这是一条连续的链条


Tags: to程序go错误errorsome语句statement
1条回答
网友
1楼 · 发布于 2024-10-03 04:32:22

只要创建一个循环,如果没有异常发生,它就会中断

while True:
   try:
       some_code_that_might_fail
    except Exception:  # catch all potential errors 
        continue  # if exception occured continue the loop
    break  # if no exception occured break out of the loop

请尝试以下示例:

while True:
    try:
        num = int(input("please enter a number"))
        print("The number is ", num)
        rec = 1 / num
    except Exception:
        print("either you entered no number or 0 (or some other error occured)")
        continue  # if any exception occured continue the loop
    break  # if no exception occured break out of the loop

print("1 / %f = %f" % (num, rec))

正如布鲁诺所提到的。 一般来说(我在自己的代码中就是这样做的),不建议捕获所有异常

您应该只显式捕获已知的异常

附录2020-04-17

阅读你的答案,我认为你的问题有点误导。 也许你的问题是,你有一个功能,你想永远运行。 但是,有时函数终止(由于错误)而不引发异常

如果是这种情况,只需写下:

while True:
   afunc()
   print("function terminated. I will restart it")

但是请注意,您的程序永远不会终止

或者,如果函数有时引发异常,有时不引发异常,但只是终止,并且您希望在函数失败或终止时调用该函数,则执行该操作

while True:
   try:
      afunc()
      print("function terminated without exception")

   except Exception:
      pass
      print("function encountered an exception")
   print("will restart")

如果您愿意,该函数可以终止,并且您可以确定它是否是错误,然后您可以执行以下操作:

while True:
   try:
      afunc()
      if i_know_that_func_terminated_correctly():
          print("function terminated correctly")
          break
      print("function terminated without an error")

   except Exception:
      pass
      print("function terminated with an exception")
   print("restarting")

我添加了用于调试/可视化的打印语句。如果不需要,只需删除或注释它们即可。(这也是我留下pass语句的原因 在except子句中)

相关问题 更多 >