exceptions with spaces don't work??

John J Lee jjl at pobox.com
Mon Apr 7 21:06:25 EDT 2003


On Mon, 7 Apr 2003, Paul Probert wrote:
> As a python newbie, I came across a problem:
> If I raise an exception with a string, as in:
>     raise 'somestring'
> then my statement
>     except 'somestring':
> will catch it unless there are spaces. For instance
> suppose I have a file ext.py:
[...]

1. Don't Do That.  String exceptions are deprecated.  Use a real exception
object instead:

class SomeError(Exception): pass

2. I think your theory about spaces in strings wouldn't stand up to some
experimentation with longer strings.  IIRC, catching a string exception
requires identity of the string objects, not mere equality -- they must be
the same object.  So:

someerror = "somestring"
try:
    raise someerror
except someerror:
    assert 1

is guaranteed to work (at least until string exceptions finally get
prohibited), while:

try:
    raise "someerror"
except "someerror":
    assert 1

is not.  Maybe it happens to work sometimes because Python is caching
short strings, so the two occurrences of "someerror" happen to be the same
object in memory.


John





More information about the Python-list mailing list