Best way to handle exceptions with try/finally

bruno at modulix onurb at xiludom.gro
Wed May 24 14:41:28 CEST 2006


Carl J. Van Arsdall wrote:
(snip)

Not an answer to your question, just a few comments on your code:

> class Shared:

class Shared(object):


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

Don't use __names unless you have a *really* strong reason to do so.
'protected' attributes are usually noted as _name.

>        def getVar(self, variableName):
>                temp = None
>                error = 0
>                self.__mutex.acquire() #accessing shared dictionary
>                try:
>                        try:
>                                temp = self.__userData[variableName]
>                        except:

Don't use bare except clauses. Specify the exceptions you intend to
handle, let the other propagate.

I once spent many hours trying to debug a badly written module that has
such a catch-all clause with a misleading error message saying some file
could not be opened when the actual problem was with a wrong login/pass
for a connection.

>                                print "Variable doesn't exist in shared
> space"

stdout is for normal program outputs. Error messages should go to stderr.

>                                raise ValueError

Should be a LookupError subclass. And the message should go with the
exception:
  raise MyLookupErrorSubclass("Variable '%s' doesn't exist in shared
space" % variableName)


>                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

The return statement is useless here.

My 2 cents.
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list