Overview of Exception Handling in Python

I have two questions about exception handling.

Q1) I'm a bit unsure when exactly the operations in else

will be performed when handling exceptions. I'm not sure when a block else

that doesn't appear in the code below will be executed :

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')

      

It's not clear why the output is:

Yasdsdsa
7.0

      

+3


source to share


2 answers


When Python encounters a return statement inside a function, it immediately returns (terminates) 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 have returned to the block try:

, thereby skipping the block execution else:

.


The second piece of code is different from what you used the block finally:

. The code inside the block is finally:

always executed, no matter if an exception is thrown, you return from a function, etc. This is done to ensure that any unoccupied code is always executed (that is, free up resources) and is not accidentally skipped.

You can read about this behavior in the docs here :

When the return

transfer control of the instruction try

with finally

that proposal finally

is performed before it actually leaves the function.

and also here :



If try

a statement return

, break

or a continue

set of instructions try...finally

, is executed in , the statement is finally

also executed "at the exit".


As for the output:

Yasdsdsa
7.0

      

and not:

7.0
Yasdsdsa

      

the answer is that the string print "Yasdsdsa"

is executed in a block finally:

before Python can print 7.0

(return value attempt_float

). Simply put, the execution path for Python is:

  • Return float(SecPrice)

    .
  • Start the block finally:

    .
  • Resume normal execution with string print attempt_float('7','3')

    and print 7.0

    .
+2


source


In the first case, you are returning within the limits try

, so you never hit the operator else

.

In the second, it finally

is executed regardless of how it ends try

. From the python docs :

The finally clause is always executed before leaving the try statement, whether an exception has occurred or not. (...) The finally clause is also executed "along the way" when any other clause of the try statement is left through a break, continue, or return statement.



Here's a good example of the order of execution:

>>> 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

      

Be sure to read the docs about exceptions!

+2


source







All Articles