Exceptions in threads?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Roy Smith

    Exceptions in threads?

    What is supposed to happen when an exception is raised and not caught in
    a thread? The Reference Manual (section 4.2) states "When an exception
    is not handled at all, the interpreter terminates execution of the
    program, or returns to its interactive main loop", but it looks like
    what really happens is the thread is terminated, not the whole program.
    If I run the following:

    -------
    #!/usr/bin/env python

    import time
    import thread

    def bogus ():
    raise Exception

    thread.start_ne w_thread (bogus, ())
    while 1:
    time.sleep (1)
    print "still alive"
    -------

    It keeps printing "still alive". This is Python 2.2.2 on RedHat 6.2
    Linux.
  • Peter Hansen

    #2
    Re: Exceptions in threads?

    Roy Smith wrote:[color=blue]
    >
    > What is supposed to happen when an exception is raised and not caught in
    > a thread? The Reference Manual (section 4.2) states "When an exception
    > is not handled at all, the interpreter terminates execution of the
    > program, or returns to its interactive main loop", but it looks like
    > what really happens is the thread is terminated, not the whole program.[/color]

    The behaviour you observed is generally what seems to happen, though
    I'm not sure it's even remotely guaranteed what the behaviour will
    be across platforms.

    If you want your threads' termination to kill the whole program, I
    think you would need to do two things. One is wrap each thread with
    a generic exception handler which catches all exceptions that aren't
    otherwise caught and sends a signal to the main thread, which would
    be set up to wait for such a signal and terminate when it got one.
    The second would be to make all threads daemon threads, so that
    when the main thread tries to terminate it doesn't wait for the
    other threads to finish as it does by default.

    None of this will, of course, help you if you have a thread blocked
    in, say, a socket connection attempt or something like that.

    -Peter

    Comment

    Working...