[Tutor] question about try & except

w chun wescpy at gmail.com
Thu Oct 27 06:32:52 CEST 2005

>         i am writing some (for me) pretty complicated stuff for work that
> really needs to work.
>         i have looked at exception handling...
> and i am using some try / except statements.
>         the problem is, that even though my script does not crash, i dont know
> the exact error.
>         is there a parameter that will allow me to use try and except but that
> will also pring out the traceback statements that python usually does to
> the terminal?

exception handling is one of the greatest strengths of Python and
other high-level languages with this feature.  it allows the
programmer to anticipate potential problems and perhaps be able to
accept and process them at runtime.

let's say you have a code block called BLOCK.  newbies to Python would
typically do something like this to ensure that errors don't happen:


however, this is not the case.  if errors *do* happen, they are thrown
away, thus serves no one any good, not the programmer nor the user.

the best solution is to catch specific exceptions and handle each
case.  (sure, and having just one handler for multiple exceptions is
also okay.).  one example is hugo's where he catches an IOError
exception and uses the exception instance 'e' to get more info out of

now if you *don't* know what exceptions may happen, you can do
something similar.  it's almost a combination of the above two

except Exception, e:
    print 'Caught exception without a specific handler:", e

this will at least tell you what exception happens in BLOCK, so that
you can modify it to be something like:

except <YourSpecificException, e:
    # handle YourSpecificException code
except Exception, e:
    print 'Caught exception without a specfic handler:', e

once you know the range of exceptions that may happen in BLOCK and
have written handlers for them, you can dispense with the general

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2006,2001

wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca

More information about the Tutor mailing list