I have two questions on exception handling.
Q1) I am slightly unsure as to when exactly the operations within else will be carried out in exception handling. I am unsure when the else block would be executed, which doesn t occur in the code below:
def attempt_float(SecPrice,diffprice):
try:
return float(SecPrice)
except:
return diffprice
else:
print "Did we succeed?"
print attempt_float( 7 , 3 )
Q2) When I run the code below:
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 )
I am unclear as to why the output is:
Yasdsdsa
7.0
When Python encounters a return-statement inside a function, it immediately returns (exits) from the function. This means that when you do:
try:
return float(SecPrice)
...
else:
print "Did we succeed?"
"Did we succeed?" will never be printed because you returned in the try: block, thereby skipping the execution of the else: block.
Your second code piece is different however because you used a finally: block. Code inside a finally: block is always executed, no matter if an exception is raised, you return from a function, etc. This is to ensure that any cleanup code which is important (i.e. frees resources) is always executed and not accidentally skipped.
https://docs.python.org/3/reference/simple_stmts.html#grammar-token-return_stmt
https://docs.python.org/3/reference/simple_stmts.html#grammar-token-return_stmt
When return passes control out of a try statement with a finally
clause, that finally clause is executed before really leaving the
function.
https://docs.python.org/3/reference/compound_stmts.html#finally
https://docs.python.org/3/reference/compound_stmts.html#finally
When a return, break or continue statement is executed in the try
suite of a try...finally statement, the finally clause is also
executed "on the way out."
As for why the output is:
Yasdsdsa
7.0
and not:
7.0
Yasdsdsa
the answer is that the print "Yasdsdsa" line is executed in the finally: block before Python is able to print 7.0 (the return value of attempt_float). Put simply, the execution path for Python is:
- Return float(SecPrice).
- Run the finally: block.
- Resume normal execution with the print attempt_float( 7 , 3 ) line and print 7.0.
http://stackoverflow.com/questions/27391809/understanding-exception-handling-in-python