How do I get info on an exception ?

Raymond Hettinger vze4rx4y at verizon.net
Sun Jul 27 02:01:57 CEST 2003


[Raymond]
> >The part that could be improved is where it talks about returning a
> >message or a tuple, as if either one but not both could occur at any
> >time.  It would be more accurate to say, that in all cases an exception
> >instance is returned; the instance has a __str__ method so it can be
> >printed as if it were a string; the instance has an attribute "args" which
> >is the tuple (errno, errmsg); and the instance has a __getitem__ method
> >so the args tuple can be directly unpacked as if the instance had been
> >the tuple itself.

[Frank]
> After checking that the input is a string, I try calling
> gethostbyname/addr depending on whether the first char is numeric and
> catch:
> "except socket.error, err:"
> Will this catch all possible errors?  I've tried feeding various
> errors into my def and caught them all so far.  Input might come from
> users at the keyboard, and crashing the program is not an option, no
> matter what is typed in.

Yes, that will catch all errors.  You have bound the instance to "err".

As I said earlier, the part of the docs that some folks may
find confusing is that part about returning a string or a tuple.
In fact, it always returns an instance that can be printed like
a string *and* unpacked like a tuple.

I'll modify the docs to make this more clear.

If you're in an experimental frame of mind, it is straight-forward to
learn exactly what is going on by adding a few print statements:

  except socket.error, inst:
       print 'Caught a', type(inst)     # show that an exception instance was
recd
       print 'The inst can be printed like a string:', inst
       errno, errmsg = inst              # show the exception can be unpacked
       print 'It contains a tuple with', errno, 'and', errmsg
       print 'Its methods are', dir(inst)
       print 'The data is kept in inst.args', inst.args
       print 'It prints because of the __str__ method:', inst.__str__()
       print 'That is my story and I am sticking with it!'


Raymond Hettinger




Raymond Hettinger






More information about the Python-list mailing list