Python program termination and exception catching

Jason Swails jason.swails at
Mon Apr 11 07:08:06 CEST 2011

On Sun, Apr 10, 2011 at 4:49 PM, Jerry Hill <malaclypse2 at> wrote:

> On Sun, Apr 10, 2011 at 3:25 PM, Jason Swails <jason.swails at>
> wrote:
> >
> > Hello everyone,
> >
> > This may sound like a bit of a strange desire, but I want to change the
> way in which a python program quits if an exception is not caught.  The
> program has many different classes of exceptions (for clarity purposes), and
> they're raised whenever something goes wrong.  Most I want to be fatal, but
> others I'd want to catch and deal with.
> >
> > Is there any way to control Python's default exit strategy when it hits
> an uncaught exception (for instance, call another function that exits
> "differently")?
> When an exception is raised and uncaught, the interpreter calls
> sys.excepthook. You can replace sys.excepthook with your own function.
>  See

This is exactly what I was looking for.  Thank you!  I can just redefine
sys.excepthook to call MPI's Abort function and print the Tracebacks;
exactly what I wanted.

MPI threading doesn't work in the same way as, for instance, the threading
modules in Python's stdlib.  It doesn't spawn additional threads from some
'main' thread.  Instead, all of the threads are launched simultaneously at
the beginning and run the same program, dividing the workload based on their
rank, so I think my application is immune to this bug.

Thanks again!

> If your program is threaded, you may need to look at this bug:
>  It describes a problem with
> replacing sys.excepthook when using the threading module, along with
> some workarounds.
> There's a simple example of replacing excepthook here:
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list