Catching a traceback

Peter Hansen peter at engcorp.com
Mon Jun 7 21:48:20 EDT 2004


EAS wrote:

> I'm wondering if there is any way to keep a program running when it runs
> into an error (using the 'try' structure) and print the traceback to the
> screen?

I'm guessing about what you want, because it's not really
clear.  If I'm right about what you want, it's not possible.
Basically, once an exception is raised by the failing code,
the code that was executing cannot be continued (as I
think you mean by "keep a program running").

If the exception was raised in very low level code, but was
not caught by any 'except' statement, the program will
terminate with an error message, as you no doubt know.
Even if you put a "default" try/except around the very
top of the program, all you are doing is catching the
exception just before it exits.  If the rest of the
program was not designed to restart in any way, that's
it.  It's done.  No "keep it running".

You can, of course, catch any exception at any level and
print tracebacks.  In fact, if this is really what you
were focusing on, then the answer to your question might be
"yes".  If you can write the code so that it does catch
an exception at the right place to allow safe continuation,
then you can certainly keep your program running, and many
people use exceptions in exactly that way.

-Peter



More information about the Python-list mailing list