how can I put an Exception as the key of a hash table

James Stroud jstroud at mbi.ucla.edu
Sat Apr 28 16:01:59 EDT 2007


yinglcs at gmail.com wrote:
> I want to keep track of the number of different exception happens in
> my python program:
> 
> ErrorHash = {}
> 
> try:
> 
>  # come code ...
> 
>  except Exception, e:
>             print e
>             errcode = e
> 
>             if (ErrorHash.has_key(errcode)):
>                 ErrorFailNo = ErrorHash[errcode]
> 
>                 ErrorHash[errcode] = ErrorFailNo + 1
> 
>             else:
>                 ErrorHash[errcode] = 1
> 
> 
> But when i print out the ErrorHash like this:
> 
> print ErrorHash
> 
> i get an empty string.  Can you please tell me how can I put an
> Exception as the key of a hash table ? Or how can i dump out all the
> content of the hashtable.
> 
> Thank you.
> 

First, you may want

       errcode = str(e)

instead of

       errcode = e


Second, the empty string is probably because the Exception is 
instantiated without a string. E.g.:

 >>> str(Exception())
''

Third, you must not be showing us everything, because an Exception can 
be used as a key, but does not give an empty string upon printing. You 
are definitely not showing us what it looks like when you print 
ErrorHash, which would be helpful.

Fourth, that you are creating a table of error codes means that you are 
attempting to transmogrify the way python handles exceptions into some 
paradigm you have used in a language like FORTRAN and thus are not using 
exceptions in their intended way. You might describe the reason you are 
generating error codes and gather suggestions about a more pythonic 
(i.e. reasonable) approach.

James



More information about the Python-list mailing list