Help on exceptions (was: Convertion of Unicode to ASCII NIGHTMARE)

Serge Orlov Serge.Orlov at gmail.com
Mon Apr 10 21:22:24 EDT 2006


ChaosKCW wrote:

> Ok I get it now. Sorry for the slowness. I have to say as a lover of
> python for its simplicity and clarity, the charatcer set thing has been
> harder than I would have liked to figure out.

I think there is a room for improvement here. In my opinion the message
is too confusing for newbies. It would be easier for them if there is a
mini tutorial available about what's going on with links to other more
broad tutorials (like unicode tutorial). Instead of generic error
----------------------
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa5 in position 0:
ordinal not in range(128)
----------------------

It can be like this. Notice special url, it is pointing to a
non-existing :) tutorial about why concatenating byte strings with
unicode strings can produce UnicodeDecodeError
----------------------
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa5 in position 0:
ordinal
not in range(128)
For additional information about this exception see:
  http://docs.python.org/2.4/exceptions/concat+UnicodeDecodeError+str
----------------------

Here is the sample code how it can be done:

---------------------------
extended_help = {
("concat", UnicodeDecodeError, str, unicode):
"http://docs.python.org/2.4/exceptions/concat+UnicodeDecodeError+str",
("concat", UnicodeDecodeError, unicode, str):
"http://docs.python.org/2.4/exceptions/concat+UnicodeDecodeError+str"
}

def get_more_help(error, key):
    if not extended_help.has_key(key):
        return
    error.reason += "\nFor additional information about this exception
see:\n  "
    error.reason += extended_help[key]


def concat(s1,s2):
    try:
        return s1 + s2
    except Exception, e:
        key = "concat", e.__class__, type(s1), type(s2)
        get_more_help(e, key)
        raise

concat(chr(0xA5),unichr(0x5432))




More information about the Python-list mailing list