What's new with Gnosis

John J. Lee jjl at pobox.com
Sat Jul 12 16:36:57 CEST 2003


"Raymond Hettinger" <vze4rx4y at verizon.net> writes:
[...]
> ACT I ---------------------------------------
> >>> s = list('abc')
> >>> try:
> ...     result = s['a']
> ... except IndexError, TypeError:
> ...     print 'Not found'
> ...
> 
> Traceback (most recent call last):
>   File "<pyshell#11>", line 2, in -toplevel-
>     result = s['a']
> TypeError: list indices must be integers

The second 'argument' of except is the caught exception object, so
that code works as if you did

try:
    result = s['a']
except IndexError, e:
    TypeError = e
    print 'Not found'


-- which doesn't catch the TypeError.



> ACT II --------------------------------------------
> >>> class MyMistake(Exception):
> ...     pass
> 
> >>> try:
> ...     raise MyMistake, 'try, try again'
> ... except MyMistake, msg:
> ...     print type(msg)
> ...
> 
> <type 'instance'>

Again, the second 'argument' of except gets the exception object, not
the string you used in the raise.

These two are equivalent [XXX er, I *think* they're always equivalent]:

raise SomeError, 'my error message'
raise SomeError('my error message')

The second form is more explicit, hence better.

Exception objects do have a __str__ method, though, so you can print
them as if they were strings:

try:
    result = s['a']
except IndexError, e:
    print e


because print calls the e.__str__ method to do its work.


> ACT III --------------------------------------------
> >>> class Prohibited(Exception):
> ...     def __init__(self):
> ...         print 'This class of should never get initialized'
> ...
> >>> raise Prohibited()
> This class of should never get initialized
> 
> Traceback (most recent call last):
>   File "<pyshell#40>", line 1, in -toplevel-
>     raise Prohibited()
> Prohibited: <unprintable instance object>
> >>> raise Prohibited
> This class of should never get initialized
> 
> Traceback (most recent call last):
>   File "<pyshell#41>", line 1, in -toplevel-
>     raise Prohibited
> Prohibited: <unprintable instance object>

These are equivalent:

raise Exception
raise Exception()

The second is more explicit, hence better.

Since exception classes always end up getting instantiated whichever
way you write the raise statement, you need to write __init__
correctly if you override it.  The Exception base class has an
__init__ that it expects to be called, so you should call it:

[At this point, I had to look up the arguments to Exception.__init__.]

class Prohibited(Exception):
    def __init__(self, *args):
        Exception.__init__(self, *args)
        print 'This class will get initialized'


In this case, the lack of that Exception.__init__ call is what's
causing the "<unprintable instance object>" message, but it could
cause other problems too.

[Actually, with your interactive example, I don't get the
"<unprintable..." bit -- maybe that's in 2.3b2...]



> ACT IV -----------------------------------------------
> >>> module = 'Root'
> >>> try:
> ...     raise module + 'Error'
> ... except 'LeafError':
> ...     print 'Need leaves'
> ... except 'RootError':
> ...     print 'Need soil'
> ... except:
> ...     print 'Not sure what is needed'
> ...
> 
> Not sure what is needed

A raised string exception only matches the string in the except
statment if both strings are the same object.  It's not enough for
them to have the same value.  Two different string literals that have
the same value aren't necessarily the same object:

myerror = "myerror"
anothererror = "myerror"  # not *necessarily* the same object as myerror
try:
    raise myerror
except anothererror:
    # we only get here if it so happens that:
    assert myerror is anothererror
except myerror:
    # we always get here, because:
    assert myerror is myerror



> ACT V -----------------------------------------------
> >>> try:
> ...     raise KeyError('Cannot find key')
> ... except LookupError, msg:
> ...     print 'Lookup:', msg
> ... except OverflowError, msg:
> ...     print 'Overflow:', msg
> ... except KeyError, msg:
> ...     print 'Key:', msg
> 
> 
> Lookup: 'Cannot find key'

except statements are checked in the order you write them.  Class
instance exceptions are matched as if by

isinstance(raised_exception, caught_exception)

so exceptions can be caught by their base classes.  LookupError is a
base class of KeyError, so the first except matches.


John




More information about the Python-list mailing list