Python:run";试一试;在异常被捕获并解决后,再次出现异常
在第一次尝试中捕获异常后,是否有方法再次输入try语句? 现在我使用“while”和“if”语句,这使得代码变得混乱。 有什么想法吗? 我会尽量简化它,抱歉没有逻辑Python:run";试一试;在异常被捕获并解决后,再次出现异常,python,Python,在第一次尝试中捕获异常后,是否有方法再次输入try语句? 现在我使用“while”和“if”语句,这使得代码变得混乱。 有什么想法吗? 我会尽量简化它,抱歉没有逻辑 run = True tryAgain = True a=0 while run: try: 2/a except Exception: if tryAgain: tryAgain = False a = 1 else: run = False 您可以尝试在t
run = True
tryAgain = True
a=0
while run:
try:
2/a
except Exception:
if tryAgain:
tryAgain = False
a = 1
else:
run = False
您可以尝试在
try
块中使用break
语句:
while True:
try:
# try code
break # quit the loop if successful
except:
# error handling
考虑到您是在
while
中执行此操作,那么您可以使用continue
继续返回while循环的开始:
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
我喜欢使用
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...
我是Python新手,所以这可能不是最佳实践。触发异常后,我返回try语句,将所有内容集中到一个函数中,然后在except语句中调用该函数
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()
希望这能解决您的问题。您希望最多再试一次,如果再试一次失败,请引发一个或多个异常(它基于ssh连接,可能需要多次尝试)