Throwing c++ exception across threads

Aaron W. LaFramboise
Wed Apr 25 15:53:00 GMT 2007

Eric Lilja wrote:

> The things is that the connection code may cause an 
> exception and I want to run that in the connection thread so the UI 
> doesn't freeze while it's waiting for an connection attempt to time-out 
> for instance.

Exceptions are a stack unwinding mechanism, and each thread has its own 
stack.  So no, threads are not normally thrown across threads, and if an 
exception 'escapes' from a thread context, it will call 
std::unexpected() and terminate the program, assuming you're using C++. 
  Something similar will happen with SEH or other sorts of exceptions.

A primary reason this effect isn't going to work easily is that it would 
involve the 'main thread' being interrupted asynchronously, while it may 
be in the middle of doing something else, and being unwound by the 
exception handler.  In general, this is not possible; C++ exceptions may 
only be thrown by certain contexts.

There may be various esoteric ways to get what you want, if you really 
wanted it; but the reality is that you almost certainly don't.  The 
strength of exceptions is in unwinding the stack and calling automatic 
destructors.  Using exceptions for general inter-thread communications 
is not appropriate.

As alternatives, I'd suggest:
-Have the main thread wait on the child thread.
-Set a condition variable.
-Release a mutex.

Unsubscribe info:
Problem reports:

More information about the Cygwin mailing list