有没有办法简化代码流程,以便busy = 0
和print busy
不必出现两次?
busy = 1
try:
print 1/0
busy = 0
print busy
except:
busy = 0
print busy
raise
答案 0 :(得分:4)
您可以将其放在finally
子句中:
try:
print 1/0
except:
raise
finally:
busy = 0
print busy
但正如@Ryan在评论中提到的那样,你在except:
条款中得到了一些无用的代码。所以你可以这样做:
try:
print 1/0
finally:
busy = 0
print busy
答案 1 :(得分:1)
好吧,您可以将公共代码放在finally
块中的try-catch块之后,如下所示:
busy = 1
try:
print 1/0
except:
raise
finally :
busy = 0
print busy
如果您想设置busy = 0
和print busy
而不管try-catch
,您可以将公共代码放在try-catch
内finally
内最终执行。
答案 2 :(得分:1)
使用finally
子句或使用except
块中的函数。
busy = 1
def final(busy):
print busy
return busy
try:
print 1/0
except:
busy = final(0) #sets busy to 0