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))
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")
只要创建一个循环,如果没有异常发生,它就会中断
请尝试以下示例:
正如布鲁诺所提到的。 一般来说(我在自己的代码中就是这样做的),不建议捕获所有异常
您应该只显式捕获已知的异常
附录2020-04-17
阅读你的答案,我认为你的问题有点误导。 也许你的问题是,你有一个功能,你想永远运行。 但是,有时函数终止(由于错误)而不引发异常
如果是这种情况,只需写下:
但是请注意,您的程序永远不会终止
或者,如果函数有时引发异常,有时不引发异常,但只是终止,并且您希望在函数失败或终止时调用该函数,则执行该操作
如果您愿意,该函数可以终止,并且您可以确定它是否是错误,然后您可以执行以下操作:
我添加了用于调试/可视化的打印语句。如果不需要,只需删除或注释它们即可。(这也是我留下
pass
语句的原因 在except
子句中)相关问题 更多 >
编程相关推荐