15

if the function called by pthread_create has the following structure

try{
  ...code....
  pthread_detach(pthread_self());
  pthread_exit(NULL);
}catch(...){
  std::cout<<"I am here"<<std::endl;
}

why does the exception handler for ellipsis get called at the execution of pthread_exit? (note that std::exception, for instance, are not thrown)

curiousguy
  • 8,038
  • 2
  • 40
  • 58
Fabio Dalla Libera
  • 1,297
  • 1
  • 10
  • 24

1 Answers1

29

At least in GCC pthread_exit might throw an ___forced_unwind exception, that is used for unwinding the stack during the thread exit. It does not inherit from std::exception, and therefore cannot be caught as one. If you do catch that exception, be sure to re-throw it so it can do its job:

try {
...
} catch (abi::___forced_unwind&) {
    throw;
} catch (...) {
    // whatever
}

The reason an exception is thrown is that pthread_exit is specified never to return. Having it throw guarantees cleanup of stack-allocated variables, and no execution of code after its location (unless you catch the unwind exception...). However this is not portable, and Clang for example uses a completely different mechanism.

BTW, this is yet another case where the catch (...) idiom does more harm than good. It is sometimes used to "stabilize" code that is throwing unknown exceptions. But that only defers the visibility of the damage to a later time and place, making it impossible to identify the real origin of the problem. The only reasonable thing to do in such a catch is minimal cleanups, possibly logging, and then rethrowing. A process that crashes due to an unhandled exception is not a pretty sight, but it can provide a debugable crash dump that clearly shows the faulty command. But that's just my grudge against catch (...), which is barely related to pthread_exit...

Giovanni Funchal
  • 8,934
  • 13
  • 61
  • 110
Eran
  • 21,632
  • 6
  • 56
  • 89
  • Thank you very much, this was exactly the case! and I guess your throw is for preventing FATAL: exception not rethrown thank you! – Fabio Dalla Libera Jul 12 '12 at 13:57
  • 2
    @Fabio: The `abi::__forced_unwind exception` can also be thrown in threads that have been canceled with `pthread_cancel`. Be careful with the ellipsis catch when terminating pthreads. – Tanner Sansbury Jul 12 '12 at 14:11
  • Very interesting, but I'd be interested to learn more on `__force_unwind` and the 2012 link is broken – Antoine Dec 29 '16 at 13:40