mardi 14 juin 2016

Python 2.7 - weird behaviour on finally clause

I've run into a very strange problem, that is making me wonder if I understand exception handling at all.

I have a code (that I'll post at the end) that looks more or less like this:

try:
    doSomething()
finally:
    print 'bye'

The code in the finally clause is not being executed when I exit my program via ctrl+c.

To make matters worse, now consider the following:

try:
    doSomething()
except:  # this could be replaced by except Exception, it doesn't matter
    print 'something'
finally:
    print 'bye'

Now the code in the except clause is not executed.. but the code in the finally clause is!

I realize this has to be the fault of the code executed by doSomething(). But my question is, how is it even possible? I thought we could be 100% confident that finally clauses always got executed.

Here goes the real code. It's running on a raspberry pi 3. It's an adaptation of the code found here.

import RPi.GPIO as GPIO, time

GPIO.setmode(GPIO.BCM)

# Define function to measure charge time
def RCtime (PiPin):
    # Discharge capacitor
    GPIO.setup(PiPin, GPIO.OUT)
    GPIO.output(PiPin, GPIO.LOW)
    time.sleep(.1)

    time1 = time.time()
    GPIO.setup(PiPin, GPIO.IN)
    if (GPIO.input(PiPin) == GPIO.LOW):
        GPIO.wait_for_edge(PiPin, GPIO.RISING, timeout=1000)
    time_elap = time.time()-time1

    return time_elap*1e3

# Main program loop
try:
    while True:
        print RCtime(4) # Measure timing using GPIO4
except Exception:
    print '---------got ya-----------------'
finally:
    print '---Finaly---'
    GPIO.cleanup() # this ensures a clean exit  

To be more specific, the behaviour depicted appears when the program is waiting at the GPIO.wait_for_edge(PiPin, GPIO.RISING, timeout=1000) line.

Aucun commentaire:

Enregistrer un commentaire