[Tutor] Exceptions and its error messages

Kent Johnson kent37 at tds.net
Wed May 25 14:49:33 CEST 2005


Jonas Melian wrote:
> I use i.e. with OSError exception the next error messages:
> err_o.strerror, err_o.filename
> 
> ::
> try:
>     (os.listdir(x))
> except OSError, err_o:
>     print "Error! %s: %r" % (err_o.strerror, err_o.filename)
> ::
> 
> But how knowing all error messages from some module?
> Is there any way of knowing from python interactive line?

If you want to print a useful message in your own exception handler, you have a couple of options. 
One is to use str(err_o):

  >>> import os
  >>> try:
  ...   os.listdir('foo')
  ... except OSError, e:
  ...   pass
  ...
  >>> e
<exceptions.WindowsError instance at 0x008D7B20>
  >>> dir(e)
['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args', 'errno', 'filename', 'strerror']
  >>> e.errno
3
  >>> e.filename
'foo/*.*'
  >>> str(e)
"[Errno 3] The system cannot find the path specified: 'foo/*.*'"

  >>> try:
  ...   import foo
  ... except ImportError, e1:
  ...   pass
  ...
  >>> e1
<exceptions.ImportError instance at 0x008D7BE8>

Notice that an ImportError does not have errno and filename attributes:
  >>> dir(e1)
['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']

but str() still gives a useful message:

  >>> str(e1)
'No module named foo'

The traceback module is very helpful:

  >>> import traceback
  >>> traceback.format_exception_only(e.__class__, e)
["WindowsError: [Errno 3] The system cannot find the path specified: 'foo/*.*'\n"]
  >>> traceback.format_exception_only(e1.__class__, e1)
['ImportError: No module named foo\n']

traceback.print_exc() will print the exception and stack trace the same as you would get if the 
exception was not caught. So a useful exception handler is
except SomeError:
   import traceback
   trackback.print_exc()

If you want finer control you could try e.g.
   import sys, traceback
   typ, value, tb = sys.exc_info()
   print '\n'.join(traceback.format_exception_only(typ, value))

HTH,
Kent



More information about the Tutor mailing list