Best way to handle exceptions with try/finally

Carl J. Van Arsdall cvanarsdall at mvista.com
Tue May 23 15:47:05 EDT 2006


Hey python people,

I'm interested in using the try/finally clause to ensure graceful 
cleanup regardless of how a block of code exits.  However, I still am 
interested in capturing the exception.

The scenario is that I have an object that accesses a global memory 
space accessible via multiple threads.  When shared resources are 
accessed a lock is acquired and then released.  In the case that someone 
tries to access a variable that doesn't exist, I still need to release 
the lock so that other threads can continue their work, but an exception 
should be raised to the caller.

Anyhow, I was playing with ideas in my code, and in this attempt I 
attempted to nest "try"s to at least make sure that accessing variables 
was raising an exception.  That's the case, and then I attempt to raise 
the exception "ValueError" so that the calling function will get the 
exception.  This doesn't work though.  It seems that any exceptions get 
caught up in that "try/finally" and i can't get the exception to raise 
higher than that without raising it outside of this try.  Is the best 
thing to do to have the exception mechanism set some type of flag that I 
can check during the "finally" statement? 

##CODE##

class Shared:
        def __init__(self):
                self.__userData= {}
                self.__mutex = threading.Lock() #lock object

        def getVar(self, variableName):
                temp = None
                error = 0
                self.__mutex.acquire() #accessing shared dictionary
                try:
                        try:
                                temp = self.__userData[variableName]
                        except:
                                print "Variable doesn't exist in shared 
space"
                                raise ValueError
                finally:
                        self.__mutex.release()
                        return temp

        def putVar(self, variableName, value):
                self.__mutex.acquire() #accessing shared dictionary
                try:
                        self.__userData[variableName] = value
                finally:
                        self.__mutex.release()
                        return

-- 

Carl J. Van Arsdall
cvanarsdall at mvista.com
Build and Release
MontaVista Software




More information about the Python-list mailing list