473,324 Members | 2,313 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Simple unicode-safe version of str(exception)?

I have code like this:
except Exception, e:
self.setState(self.Failed, str(e))
which fails if the exception contains a unicode argument.

I did, of course, try unicode(e) but that fails.

The following works, but seems rather messy:

except Exception, e:
errStr = ",".join([unicode(s) for s in f.args])
self.setState(self.Failed, errStr)

Is there a simpler solution that works in Python 2.3-2.5?

-- Russell
Jun 27 '08 #1
14 1469
Russell E. Owen wrote:
I have code like this:
except Exception, e:
self.setState(self.Failed, str(e))
which fails if the exception contains a unicode argument.
Fails how?
I did, of course, try unicode(e) but that fails.
Converting unicode to unicode doesn't help. Instead of just e, try
using e.encode("some-encoding") where some-encoding should be your
system's default encoding like utf-8 or iso8859-1.

Regards,
Björn

--
BOFH excuse #434:

Please state the nature of the technical emergency

Jun 27 '08 #2
>I have code like this:
>except Exception, e:
self.setState(self.Failed, str(e))
which fails if the exception contains a unicode argument.

Fails how?
ASCII encoding error, I suppose. It fails only if a) one argument
is a Unicode object, and b) that Unicode object contains non-ASCII
parameters.
>I did, of course, try unicode(e) but that fails.

Converting unicode to unicode doesn't help.
e is an exception object, not a Unicode object.

Regards,
Martin

Jun 27 '08 #3
In article <48**************@v.loewis.de>,
"Martin v. Löwis" <ma****@v.loewis.dewrote:
I have code like this:
except Exception, e:
self.setState(self.Failed, str(e))
which fails if the exception contains a unicode argument.
Fails how?

ASCII encoding error, I suppose. It fails only if a) one argument
is a Unicode object, and b) that Unicode object contains non-ASCII
parameters.
Seem ironic that this fails even though pretty nearly anything
else is a valid input to str() -- socket, dict, whatever?

A sort of generic solution might be to follow str's behavior
with respect to '__str__', extending it to fall back to repr()
whatever goes wrong.
def xtr(a):
try:
return str(a)
except:
return repr(a)

...
self.setState(self.Failed, xtr(e))

Donn Cave, do**@u.washington.edu
Jun 27 '08 #4
"Martin v. Löwis" wrote:
e is an exception object, not a Unicode object.
Er, sure, thanks for pointing that out. At first sight he should
substitute "e" with "e.message" then since he tries to convert to
string (for display?).

Regards,
Björn

--
BOFH excuse #366:

ATM cell has no roaming feature turned on, notebooks can't connect

Jun 27 '08 #5
In article <67*************@mid.individual.net>,
Bjoern Schliessmann <us**************************@spamgourmet.com>
wrote:
"Martin v. Löwis" wrote:
e is an exception object, not a Unicode object.

Er, sure, thanks for pointing that out. At first sight he should
substitute "e" with "e.message" then since he tries to convert to
string (for display?).
No. e.message is only set if the exeption object receives exactly one
argument.

That is why my replacement code reads:
errStr = ",".join([unicode(s) for s in f.args])
self.setState(self.Failed, errStr)
(where e is an Exception of some kind)

Notice that I'm iterating over the args. But again, this is far messier
than:
self.setState(self.Failed, str(e)

So...to repeat the original question, is there any simpler unicode-safe
replacement for str(exception)?

-- Russell
Jun 27 '08 #6
In article <do************************@gnus01.u.washington.ed u>,
Donn Cave <do**@u.washington.eduwrote:
In article <48**************@v.loewis.de>,
"Martin v. Löwis" <ma****@v.loewis.dewrote:
>I have code like this:
>except Exception, e:
> self.setState(self.Failed, str(e))
>which fails if the exception contains a unicode argument.
>
Fails how?
ASCII encoding error, I suppose. It fails only if a) one argument
is a Unicode object, and b) that Unicode object contains non-ASCII
parameters.

Seem ironic that this fails even though pretty nearly anything
else is a valid input to str() -- socket, dict, whatever?
I agree. In fact str(a) works if a is a dict or list that contains
unicode data! Pity the same is not true of exceptions.

Should I report this as a bug? I suspect it's a misfeature.
A sort of generic solution might be to follow str's behavior
with respect to '__str__', extending it to fall back to repr()
whatever goes wrong.
def xtr(a):
try:
return str(a)
except:
return repr(a)
Yes. That is a more flexible alternative to what I've adopted:
def exStr(ex):
return ",".join([unicode(s) for s in f.args])
the latter gives better output for the case I'm interested in, but only
handles exceptions.

Oh well. I'll stick to my solution and hope that Python 2.6 and 3.0 fix
the problem in a more sensible fashion.

-- Russell
Jun 27 '08 #7
Hallöchen!

Russell E. Owen writes:
[...]

So...to repeat the original question, is there any simpler
unicode-safe replacement for str(exception)?
Please show us the tracebacks you get becuae unicode(s) must fail,
too, if there are non-ASCII characters involved.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jabber ID: br*****@jabber.org
(See http://ime.webhop.org for further contact info.)
Jun 27 '08 #8
Russell E. Owen <ro***@cesmail.netwrote:
>No. e.message is only set if the exeption object receives exactly one
argument.
And not always then:
>>e1 = Exception(u"\u00fe")
e1.message
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: Exception instance has no attribute 'message'
>That is why my replacement code reads:
errStr = ",".join([unicode(s) for s in f.args])
errStr = ",".join(e.args)

There is something distinctly odd going on here, though:
>>str(e1)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xfe' in position 0: ordinal not in range(128)
>>e2 = Exception(u"\u00fe", "foo")
str(e2)
"(u'\\xfe', 'foo')"
>>>
--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Jun 27 '08 #9
In article <87************@physik.rwth-aachen.de>,
Torsten Bronger <br*****@physik.rwth-aachen.dewrote:
Hallöchen!

Russell E. Owen writes:
[...]

So...to repeat the original question, is there any simpler
unicode-safe replacement for str(exception)?

Please show us the tracebacks you get becuae unicode(s) must fail,
too, if there are non-ASCII characters involved.
Why?

What I am trying to do is get a unicode representation of the arguments
of an exception. str(e), the obvious solution, fails if the exception
contains one argument that is a unicode string that cannot be decoded to
ASCII:

UnicodeEncodeError: 'ascii' codec can't encode character...ordinal not
in range(128)

What I do with the resulting unicode string afterwards is a different
issue. (As a matter of fact I display it on a widget that can display
unicode, but if I tried to print it to my Mac Terminal it would complain
about the non-ASCII characters--something I should look into fixing
someday).

But in any case, here are the exceptions you wanted to see. This is
using Python 2.5.2 on a Mac:
>>d =u"\N{DEGREE SIGN}"
d
u'\xb0'
>>str(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in
position 0: ordinal not in range(128)
>>e = Exception(d)
str(e)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in
position 0: ordinal not in range(128)
>>e
Exception(u'\xb0',)
>>",".join([unicode(s) for s in e.args])
u'\xb0'
>>>
Based on the dearth of better replacements I've gone with the solution
that is shown as the last line above, coded as the following function
(incorporating Donn Cave's excellent suggestion to use repr as a
fallback). It has the minor issue that it can mask KeyboardInterrupt on
older versions of Python but it's close enough. A lot of work to replace
str(exc).

def strFromException(exc):
"""Unicode-safe replacement for str(exception)"""
try:
return str(exc)
except Exception:
try:
return ",".join([unicode(s) for s in exc.args])
except Exception:
# in case exc is some unexpected type
return repr(exc)

-- Russell
Jun 27 '08 #10
Hallöchen!

Russell E. Owen writes:
Torsten Bronger <br*****@physik.rwth-aachen.dewrote:
>Russell E. Owen writes:
>>[...]

So...to repeat the original question, is there any simpler
unicode-safe replacement for str(exception)?

Please show us the tracebacks you get becuae unicode(s) must
fail, too, if there are non-ASCII characters involved.

Why?

[...]
>>>",".join([unicode(s) for s in e.args])
u'\xb0'
I though you wanted to have a string. But this is again a unicode.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jabber ID: br*****@jabber.org
(See http://ime.webhop.org for further contact info.)
Jun 27 '08 #11
Hallöchen!

Russell E. Owen writes:
Torsten Bronger <br*****@physik.rwth-aachen.dewrote:
>Russell E. Owen writes:
>>[...]

So...to repeat the original question, is there any simpler
unicode-safe replacement for str(exception)?

Please show us the tracebacks you get becuae unicode(s) must
fail, too, if there are non-ASCII characters involved.

Why?

[...]
>>>",".join([unicode(s) for s in e.args])
u'\xb0'
I thought you wanted to have a string. But this is again a unicode.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jabber ID: br*****@jabber.org
(See http://ime.webhop.org for further contact info.)
Jun 27 '08 #12
Should I report this as a bug? I suspect it's a misfeature.

Please no. There isn't much that can be done about it, IMO.

Regards,
Martin
Jun 27 '08 #13
Hallöchen!

Martin v. Löwis writes:
>Should I report this as a bug? I suspect it's a misfeature.

Please no. There isn't much that can be done about it, IMO.
One could give Exception a __unicode__ method. On the other hand,
this kind of conversion of an exception to something printable is a
quite ugly kludge anyway in my opinion, so it needn't special
support.

Tschö,
Torsten.

--
Torsten Bronger, aquisgrana, europa vetus
Jabber ID: br*****@jabber.org
(See http://ime.webhop.org for further contact info.)
Jun 27 '08 #14
Jim
I often struggle with the problem outlined in part in this thread. I
know that I'm going to repeat some of what is said elsewhere but I'd
like to present the question all in one place.

I believe that the routines in the Python standard library do not
document which exceptions they could raise (I understand some reasons
why, but they nontheless do not). So I often find out the hard way
that a library call can raise an exception that I was not smart enough
to anticipate. So I often find myself doing
try:
make_a_routine_call(x,y,z)
except AnticipatedError, err:
do_something_with_it(x,y,z,err)
exception Exception, err:
print "something crazy happened "+str(err)
where the print statement is just supposed to give me some idea of
what happened. (I actually usually log it instead of printing it. If
there is a better way, I'd love to hear it.) But "str(err)" sometimes
fails, as the OP noted.

Further, xtr(err) alone is not enough, I believe. I believe that some
routines in the standard library do not return strings (by that I mean
something approximately like "err.value is a pair"; forgive me, I
don't remember the full details).

Surely as lovely a language as Python has a better idiom for dealing
with exceptions in the standard library than something that works out
to
print "something crazy happened"+" ".join([xtra(x) for x in err])
? (I would understand better if it was a user's code; they are free
to do what works for them, of course.) But I've been unable to think
of one and I haven't seen in this thread another direction. Is there
one?

Jim
Jun 27 '08 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
by: aurora | last post by:
I have long find the Python default encoding of strict ASCII frustrating. For one thing I prefer to get garbage character than an exception. But the biggest issue is Unicode exception often pop up...
10
by: JKop | last post by:
Let's say you've a very simple function, that, if it fails, should throw an exception. The thing is though, it's not important enough to go and actually define an "exception class" for, so... is...
1
by: War Eagle | last post by:
I have this line of code I want to know where to put it in my code (basically so any private function using clientSocket.Send or clientSocket.Receive will accept it): Socket clientSocket = new...
1
by: Mike P | last post by:
I have created my own very simple exception classes e.g using System; namespace WebApplication90 { public class AddressException : ApplicationException { public AddressException() {
3
by: utab | last post by:
Dear all, I have been reading on exceptions and had a very simple exception example with terminate. But one point was fuzzy to me. Why is the block not executed. Because of the dtor throws...
14
by: Dennis Benzinger | last post by:
Hi! The following program in an UTF-8 encoded file: # -*- coding: UTF-8 -*- FIELDS = ("Fächer", ) FROZEN_FIELDS = frozenset(FIELDS) FIELDS_SET = set(FIELDS)
13
by: gabor | last post by:
hi, from the documentation (http://docs.python.org/lib/os-file-dir.html) for os.listdir: "On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode...
2
by: John Nagle | last post by:
Here's a strange little bug. "socket.getaddrinfo" blows up if given a bad domain name containing ".." in Unicode. The same string in ASCII produces the correct "gaierror" exception. Actually,...
1
by: nkarkhan | last post by:
Hello, I have a list of strings, some of the strings might be unicode. I am trying to a .join operation on the list and the .join raises a unicode exception. I am looking for ways to get around...
18
by: Bart Friederichs | last post by:
Hi, I was just browsing the C++ FAQ and stumbled upon the 'mind sets' that are wrong for using C++ exception handling. I am looking for the 'right' mind set. I come from a C background, and...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.