Help with trapping an exception

Phil Frost indigo at
Tue Aug 24 03:13:48 CEST 2004

Take a look at the traceback standard module to format exceptions
nicely. Another thing you can do is this:

except Exception, x:
  print x

That asigns the exception to x in the except block. All exceptions can
be converted to strings which are usually short descriptions of the
problem. One problem is KeyError, which converts to just the bad key,
for example the above just prints "fu" which is less than helpful.
Another catch of the above is that it will only catch subclasses of
Exception, which is almost everything except a few like StopIteration or
user classes that don't subclass Exception.

On Mon, Aug 23, 2004 at 09:05:15PM -0400, pythos at wrote:
> I have a piece of code like this:
> try:
> 	some code
> except:
> 	print >> sys.stderr, "error: ", sys.exc_info()
> When an exception is thrown from the code, what I see on the console is this:
> error: (<class exceptions.NameError at 0x01E7A378>, <exceptions.NameError
> instance at 0x09752C50>, <traceback object at 0x096A1408>)
> I had a lot of trouble figuring out what was causing the NameError.  I finally
> figured it out by removing the "try" and "except" statements so that my code
> didn't catch any exceptions.  When I did that, I saw the following on my
> console:
> Traceback (most recent call last):
>   File "c:\Documents and Settings\xxxxx\rot.PspScript", line 79, in Do
>     os.path.walk(baseDirectory, ProcessDirectory, Environment)
>   File "c:\Program Files\xxxxxx\Python Libraries\lib\", line 318, in
> walk
>     func(arg, top, names)
>   File "c:\Documents and Settings\xxxxx\rot.PspScript", line 36, in
> ProcessDirectory
>     App.Do(Environment, 'FileOpen', {
> NameError: global name 'Environment' is not defined
> Now that was much more helpful.  Once I knew that 'Environment' was not
> defined, I easily figured out the problem.  But I need to use "try" and
> "except" to catch the exception, otherwise my program will end abruptly
> without finishing.  So how can I see the "NameError: global name 'Environment'
> is not defined" message in the "except" section of my code?  A call to
> sys.exc_info() doesn't show it.  Is there another function I can use?  Thanks.

More information about the Python-list mailing list