我有两个关于异常处理的问题。
Q1) 我有点不确定 else
中的操作究竟何时会在异常处理中执行。我不确定何时执行 else
block ,这不会出现在以下代码中:
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
print attempt_float('7','3')
Q2) 当我运行下面的代码时:
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
最佳答案
当 Python 在函数中遇到 return 语句时,它会立即从函数中返回(退出)。这意味着当您这样做时:
try:
return float(SecPrice)
...
else:
print "Did we succeed?"
“Did we succeed?”
将永远不会被打印,因为您在 try:
block 中返回,从而跳过了 else:
的执行> 阻止。
但是您的第二个代码段有所不同,因为您使用了 finally:
block 。 finally:
block 中的代码始终 执行,无论是否引发异常、您从函数返回等。这是为了确保任何清理代码important(即释放资源)总是被执行并且不会被意外跳过。
您可以在文档中阅读此行为 here :
When
return
passes control out of atry
statement with afinally
clause, thatfinally
clause is executed before really leaving the function.
以及here :
When a
return
,break
orcontinue
statement is executed in thetry
suite of atry...finally
statement, thefinally
clause is also executed "on the way out."
至于为什么输出是:
Yasdsdsa
7.0
而不是:
7.0
Yasdsdsa
答案是 print "Yasdsdsa"
行在 Python 能够打印 7.0
之前在 finally:
block 中执行( attempt_float
的返回值)。简单来说,Python的执行路径是:
- 返回
float(SecPrice)
。 - 运行
finally:
block 。 - 使用
print attempt_float('7','3')
行恢复正常执行并打印7.0
。
关于python - 了解 Python 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27391809/