Python seems to be ignoring my except clause...

Larry Bates larry.bates at websafe.com
Wed Feb 20 09:09:17 EST 2008


Adam W. wrote:
> I am trying to handle a Unicode error but its acting like the except
> clause is not even there.  Here is the offending code:
> 
>         def characters(self, string):
>             if self.initem:
>                 try:
>                     self.data.append(string.encode())
>                 except:
>                     self.data.append('No habla la Unicode')
> 
> And the exception:
> 
>   File "C:\Users\Adam\Desktop\XMLWorkspace.py", line 65, in characters
>     try:
> UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in
> position 83: ordinal not in range(128)
> 
> Its got to be something really dumb I'm missing, this make no sence.

Seems that others have addressed you specific problem so I wanted to take this 
opportunity to save you from hours of frustration in the future (trust me on 
this one).  It is almost NEVER a good idea to use a blank except: clause in your 
code.  The problem is that it catches ALL exceptions, not just the one you are 
trying to catch.  It is much better to determine the exception you are trying to 
catch here.

Example:

try:
     self.data.append(string.encode())
except UnicodeEncodeError:
     self.data.append('No habla la Unicode')


You can spend a lot of time trying to figure out what is going on when your 
blank except catches all the exceptions.  This lets the other exceptions do what 
they should do.

Hope this helps.

Larry Bates



More information about the Python-list mailing list