理解Python中的异常处理
我有两个关于异常处理的问题 Q1我有点不确定else中的操作何时会在异常处理中执行。我不确定何时执行else块,这在下面的代码中没有出现:理解Python中的异常处理,python,function,exception,exception-handling,Python,Function,Exception,Exception Handling,我有两个关于异常处理的问题 Q1我有点不确定else中的操作何时会在异常处理中执行。我不确定何时执行else块,这在下面的代码中没有出现: def attempt_float(SecPrice,diffprice): try: return float(SecPrice) except: return diffprice else: print "Did we succeed?" print attempt_float(
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
print attempt_float('7','3')
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
finally:
print "Yasdsdsa"
print attempt_float('7','3')
Q2当我运行下面的代码时:
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
print attempt_float('7','3')
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
finally:
print "Yasdsdsa"
print attempt_float('7','3')
我不清楚为什么输出是:
Yasdsdsa
7.0
Yasdsdsa
7.0
在第一种情况下,您在try中返回,因此您永远不会点击else语句 在第二个示例中,无论try如何退出,都将执行finally。从: 无论是否发生异常,finally子句总是在离开try语句之前执行。。。当try语句的任何其他子句通过break、continue或return语句留下时,finally子句也在“中途”执行 以下是执行顺序的一个很好的示例:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print "division by zero!"
... else:
... print "result is", result
... finally:
... print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
请务必阅读有关异常的文档 当Python在函数中遇到return语句时,它会立即返回函数的出口。这意味着当您执行以下操作时:
try:
return float(SecPrice)
...
else:
print "Did we succeed?"
我们成功了吗?将永远不会打印,因为您在try:块中返回,从而跳过else:块的执行
然而,您的第二个代码段是不同的,因为您使用了finally:块。始终执行finally:块中的代码,无论是否引发异常、是否从函数返回等。这是为了确保始终执行任何重要的清理代码,即释放资源,而不是意外跳过
您可以在以下两个文档中了解此行为:
当return用finally将控件从try语句中传递出去时
子句,该finally子句在真正离开
功能
以及:
在try中执行return、break或continue语句时
try…finally语句的套件,finally子句也是
在离开的路上被处决
至于为什么输出是:
Yasdsdsa
7.0
Yasdsdsa
7.0
而不是:
7.0
Yasdsdsa
答案是print Yasdsdsa行是在finally:块中执行的,然后Python才能打印7.0 trument_float的返回值。简而言之,Python的执行路径是:
返回价格。
运行finally:块。
使用打印尝试_float'7','3'行和print 7.0恢复正常执行。
你在试一试中就回来了,这样你就再也不会碰到其他可能重复的感谢了。我主要不明白为什么输出的顺序是这样的:Yasdsdsa 7.0,而不是相反。谢谢。如果finally仅在退出时执行,为什么输出的顺序是:Yasdsdsa 7.0,而不是相反。因为您正在打印从trunt_float返回的值,但在它返回之前,finally块被执行。