问题
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)
回答1:
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
...
来源:https://stackoverflow.com/questions/11452546/why-does-pthread-exit-throw-something-caught-by-ellipsis