在第一次尝试中捕获异常后,有没有办法再次输入try语句? 现在我正在使用"而#34;和"如果"声明,它使代码混乱。 有任何想法吗? 会尽量简化它,抱歉没有逻辑......
run = True
tryAgain = True
a=0
while run:
try:
2/a
except Exception:
if tryAgain:
tryAgain = False
a = 1
else:
run = False
答案 0 :(得分:4)
您可以尝试在break
区块中使用try
语句:
while True:
try:
# try code
break # quit the loop if successful
except:
# error handling
答案 1 :(得分:2)
考虑到您是在continue
中执行此操作,那么您可以使用tryAgain = True
a=0
while True:
try:
2/a
break # if it worked then just break out of the loop
except Exception:
if tryAgain:
continue
else:
# whatever extra logic you nee to do here
继续回到while循环的开头:
{{1}}
答案 2 :(得分:1)
我喜欢使用for
循环,以便尝试和尝试不会永远继续下去。然后循环的else
子句是放置"我放弃"的地方。码。这是一个支持' n'重试> 1:
a=0
num_tries = 5
for try_ in range(0,num_tries):
try:
2/a
except Exception:
print("failed, but we can try %d more time(s)" % (num_tries - try_ - 1))
if try_ == num_tries-2:
a = 1
else:
print("YESS!!! Success...")
break
else:
# if we got here, then never reached 'break' statement
print("tried and tried, but never succeeded")
打印:
failed, but we can try 4 more time(s)
failed, but we can try 3 more time(s)
failed, but we can try 2 more time(s)
failed, but we can try 1 more time(s)
YESS!!! Success...
答案 3 :(得分:0)
我是Python的新手,所以这可能不是最佳实践。通过将所有内容集中到一个函数中,然后在except语句中调用该函数,触发异常后,我返回到try语句。
def attempts():
while True:
try:
some code
break #breaks the loop when sucessful
except ValueError:
attempts() #recalls this function, starting back at the try statement
break
attempts()
希望这能解决您的问题。