Inject runtime exception to pthread sometime fails. How to fix that? - c++

I try to inject the exception to thread using signals, but some times the exception is not get caught. For example the following code:
void _sigthrow(int sig)
{
throw runtime_error(strsignal(sig));
}
struct sigaction sigthrow = {{&_sigthrow}};
void* thread1(void*)
{
sigaction(SIGINT,&sigthrow,NULL);
try
{
while(1) usleep(1);
}
catch(exception &e)
{
cerr << "Thread1 catched " << e.what() << endl;
}
};
void* thread2(void*)
{
sigaction(SIGINT,&sigthrow,NULL);
try
{
while(1);
}
catch(exception &e)
{
cerr << "Thread2 catched " << e.what() << endl; //never goes here
}
};
If I try to execute like:
int main()
{
pthread_t p1,p2;
pthread_create( &p1, NULL, &thread1, NULL );
pthread_create( &p2, NULL, &thread2, NULL );
sleep(1);
pthread_kill( p1, SIGINT);
pthread_kill( p2, SIGINT);
sleep(1);
return EXIT_SUCCESS;
}
I get the following output:
Thread1 catched Interrupt
terminate called after throwing an instance of 'std::runtime_error'
what(): Interrupt
Aborted
How can I make second threat catch exception?
Is there better idea about injecting exceptions?

G++ assumes that exceptions can only be thrown from function calls. If you're going to violate this assumption (eg, by throwing them from signal handlers), you need to pass -fnon-call-exceptions to G++ when building your program.
Note, however that this causes G++ to:
Generate code that allows trapping instructions to throw
exceptions. Note that this requires platform-specific runtime
support that does not exist everywhere. Moreover, it only allows
_trapping_ instructions to throw exceptions, i.e. memory
references or floating point instructions. It does not allow
exceptions to be thrown from arbitrary signal handlers such as
`SIGALRM'.
This means that exceptioning out from the middle of some random code is NEVER safe. You can only except out of SIGSEGV, SIGBUS, and SIGFPE, and only if you pass -fnon-call-exceptions and they were triggered due to a fault in the running code. The only reason this worked on thread 1 is because, due to the existence of the usleep() call, G++ was forced to assume that it might throw. With thread 2, G++ can see that no trapping instruction was present, and eliminate the try-catch block.
You may find the pthread cancellation support more akin to what you need, or otherwise just add a test like this somewhere:
if (*(volatile int *)terminate_flag) throw terminate_exception();

In Boost.thread a thread can be interrupted by invoking the interrupt() member function of the corresponding boost::thread object. It uses pthread condition variables to communicate with the thread and allows you to define interruption points in the thread code. I would avoid use of pthread_kill in C++. The fact that boost thread doesn't use pthread_kill anywhere in their code confirms this I think.

Related

can't catch exception in main thread when other thread active and has try-catch

Main thread can't catch an exception (that was thrown in the main thread) while another thread with try-catch is still active. How to solve it?
example:
int main()
{
// try-catch of main thread
try
{
// run a thread
std::thread cThread([]()
{
// try-catch of secondary thread
try
{
// makes thread works for 500 ms in order main thread will call
// throw while thread is still active.
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
catch (...)
{
}
});
// Any call to throw BEFORE thread is finished, won't be catch.
// HOW TO SOLVE IT??
throw 1;
// wait thread finished
cThread.join();
// IF YOU PUT THE "throw 1" HERE (AFTER THREAD FINISHED), IT WILL BE
// CATCH.
}
catch (int e)
{
std::cout << "Catched exception " << e << " in main";
}
return 0;
}
It's not so much that the exception isn't caught as it is that destroying a joinable thread terminates the process.
So your program terminates before the exception handler can be executed.
If you declare the thread outside the try-catch block, the exception will be caught.
Remember that you also need to join the thread if the exception was thrown.
You've got something wrong. I mean, you've misunderstood something.
It can't be about try-catch. 'throw' and 'try-catch' are intra-thread things, they live only on the current thread, whatever it would be at the moment of throwing, main thread or the other.
Another thread cannot catch exception thrown from current thread. Exceptions does not cross threads, unless you really want it and implement it as, for example, something on current thread catches the exception and passed them to other thread and then re-throws/etc these exceptions there. You don't have any such things, so it cannot be it.
You have a join() call after the throw, and you expect that throw 1 will skip over it. That's true. However, there's also the std::thread cThread variable in the scope.
Since the thread is running, and due to throw 1 the thread has never been join()ed yet, then the expected thing to see would be program termination (see https://stackoverflow.com/a/13984169/717732), because the destructor of std::thread would detect the un-join()ed thread. That means, the std::cout << "Catched exception " << e << " in main"; should never be called. Even if the thread has somehow finished, your program should still terminate, since it does not change the fact it was not join()ed (see https://en.cppreference.com/w/cpp/thread/thread/joinable)
However, depending on library, compiler, debugger, etc, the effect you see may differ. For example, if you run it in a debugger, it may wait until all threads finish, and you'd get the effect of "waiting until inner thread finished". Hard to say.
If you actually see the "Catched exception " << e << " line running, the you've got a real problem. Either you are running something else than your current code, or your stdlib is broken. A broken stdlib might for example do a silent join() in the destructor of std::thread instead of terminating the program. Who knows. Broken lib can do many things.
Thanks to molbdnilo and quetzalcoatl.
I now made the code works by using std::async instead of std::thread:
First, the problem is not related to try-catch in the thread. It was mine mistake to think it is. So here is a failure code:
int main()
{
// try-catch of main thread
try
{
// run a thread
std::thread cThread([]()
{
});
// Any call to throw BEFORE thread join won't be catch.
// HOW TO SOLVE IT??
throw 1;
// wait thread finished
cThread.join();
// IF YOU PUT THE "throw 1" HERE (AFTER THREAD FINISHED), IT WILL BE
// CATCH.
}
catch (int e)
{
std::cout << "Catched exception " << e << " in main";
}
return 0;
}
And a code that works:
int main()
{
std::future<void> cF;
// try-catch of main thread
try
{
// run a thread
cF = std::async(std::launch::async, []()
{
});
// You can call throw , it will be catch :)
throw 1;
// wait thread finished
if (cF.valid())
{
cF.get();
}
}
catch (int e)
{
std::cout << "Catched exception " << e << " in main";
}
return 0;
}

Exception not caught after signal

I try to catch a termination signal to my code to write a restart file before exiting. My solution is based on this answer.
#include <exception>
#include <csignal>
#include <iostream>
class InterruptException : public std::exception
{
public:
InterruptException(int _s) : signal_(_s) { }
int signal() const noexcept
{
return this->signal_;
}
private:
int signal_;
};
/// method to throw exception at signal interrupt
void sig_to_exception(int s)
{
throw InterruptException(s);
}
int main()
{
// activate signal handling
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = sig_to_exception;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
sigaction(SIGINT, &sigIntHandler, NULL);
try
{
for (std::size_t i = 0; i < 100000000; ++i)
{
std::cout << i << std::endl;
}
}
catch (const InterruptException& e)
{
std::cout << "Received signal " << e.signal() << std::endl;
std::exit(1);
}
catch(...)
{
std::cout << "Other catch!" << std::endl;
}
}
The exception gets thrown fine, however, my catch block does not catch it. The program terminates with an uncaught exception InterruptException. I tried with clang and gcc on MacOS. Any idea why the exception is not caught correctly?
Thanks
Output when compiled with g++ 7.3.0:
terminate called after throwing an instance of 'InterruptException'
what(): std::exception
Abort trap: 6
Output when compiled with Apple LLVM 9.0.0
libc++abi.dylib: terminating with uncaught exception of type InterruptException: std::exception
PS: It seems when I compile with Apple LLVM the exception gets caught sometimes, but not all the time, which makes this even weirder.
There is very little that you can reliably do in a signal handler. In particular, you cannot throw an exception. The code in the question (and the "answer" that it links to) relies, at best, on compiler/OS-specific behavior. For the limits on what you can do in a signal handler, see this.
Note that the link above refers to signal, which is standard C. sigaction is not standard C, it's POSIX, and the C++ language definition doesn't impose any requirements on a program that uses it.
On most system the stack frame used by the signal handler is not a standard function stack frame as defined by the compiler for function calls.
So throwing out of a sig handler is not supported.
Stack frame for signal handling in the Linux Kernel
From the discussion in the linked question, on a linux system they are not even using the same stack for the stack frame and returning requires jumping back to a system function to restore the original user stack.
Unless the OS is specifically designed to handle exceptions then this is not going to work.
The rule of thumb for signal handlers is to do as little as possible in a signal handler. Set a global flag that can be detected by your normal code then check that flag periodically in your normal code to see when the signal has happened.

How to print something when runtime error occurs somewhere in my C++ code?

What normally happens is when code faces Runtime error , it simply terminates with runtime flag , what i intend to do is print a custom message before termination & i wish to 'return 0' ,ie terminate code normally after printing custom message as if runtime never happened .
Any idea how to do it?
There are different reasons, why a programm might terminate.
First: An uncaught Exception was thrown. If that is, what you are looking for, then follow the advice, Paul Evans has given. With C++11, you might want to call get_terminate(), and call the returned teminate handler at the end of your new teminate handler:
terminate_handler old_terminate_handler = nullptr;
void new_terminate_handler() {
std::cerr << "terminate due to error" << std::endl;
if( old_terminate_handler != nullptr ) {
old_terminate_handler();
} else {
std::abort();
}
}
int main(int, char**) {
old_terminate_handler = get_terminate();
set_terminate(new_terminate_handler);
}
Second: a signal was received, that would normaly terminate the program. Install a signal handler to catch it:
void sig_handler(int signal) {
new_terminate_handler();
}
// ...
std::signal(SIGTERM, sig_handler);
std::signal(SIGSEGV, sig_handler);
std::signal(SIGINT, sig_handler);
// ...
Third: The operating system might simply decide to kill the process. That is either done by a normal signal signal (e.g. SIGTERM), or by a signal, that can not be handled (e.g. SIGKILL) In the second case, you have no chance to notice that inside the programm. The first case is already covered.
First define your custom terminate handler, something like:
void f() {
std::cout << \\ your custom message
}
then you want to call:
std::terminate_handler set_terminate( std::terminate_handler f );
to set up your function f as the terminate handler.

Properly terminating program. Using exceptions

Question:
Is using exceptions the proper way to terminate my program if all I want is to display an error message and close (accounting that I may be deep in the program)? Or can I just explicitly call something like exit(EXIT_FAILURE) instead?
What I'm Currently Doing:
I'm working on a game project and am trying to figure out the best way to terminate the program in the case of an error that calls for such an action. For example, in the case the textures can't be loaded I display an error message and terminate the program.
I'm currently doing this with exceptions like so:
int main()
{
Game game;
try
{
game.run();
}
catch (BadResolutionException & e)
{
Notification::showErrorMessage(e.what(), "ERROR: Resolution");
return 1;
}
catch (BadAssetException & e)
{
Notification::showErrorMessage(e.what(), "ERROR: Assets");
return 1;
}
catch (std::bad_alloc & e)
{
Notification::showErrorMessage(e.what(), "ERROR: Memory");
return 1;
}
return 0;
}
All but bad_alloc are my own defined exceptions derived from runtime_error.
I don't need any manual resource cleanup and I'm using std::unique_ptr for any dynamic allocation. I just need to display the error message and close the program.
Research/Alternatives to Exceptions:
I've looked up a lot of posts on SO and other places and have seen others say anything from don't use exceptions, to use exceptions but your using them wrong. I've also looked up explicitly calling something like exit().
Using exit() sounds nice but I read it won't go back through the call stack up to main cleaning everything up (if I can find this again I'll post the link). Additionally, according to http://www.cplusplus.com/reference/cstdlib/exit/ this should not be used if multiple threads are active. I do expect to be creating a second thread for a short time at least once, and an error could occur in that thread.
Not using exceptions was mentioned in some replies here in relation to games https://gamedev.stackexchange.com/questions/103285/how-industy-games-handle-their-code-errors-and-exceptions
Use exceptions was discussed here: http://www.quora.com/Why-do-some-people-recommend-not-using-exception-handling-in-C++
There are a number of other sources I've read but those were the most recent I looked at.
Personal Conclusion:
Due to my limited experience of working with error handling and using exceptions, I'm not sure if I'm on the right track. I've chosen the route of using exceptions based on the code I posted above. If you agree that I should tackle those cases with exceptions, am I using it correctly?
It's generally considered good practice to let all exceptions propagate through to main. This is primarily because you can be sure the stack is properly unwound and all destructors are called (see this answer). I also think it's more organised to do things this way; you always known where your program will terminate (unless the program crashes). It's also facilitates more consistent error reporting (a point often neglected in exception handling; if you can't handle the exception, you should make sure your user knows exactly why). If you always start with this basic layout
int main(int argc, const char **argv)
{
try {
// do stuff
return EXIT_SUCCESS;
} catch (...) {
std::cerr << "Error: unknown exception" << std::endl;
return EXIT_FAILURE;
}
}
then you won't go far wrong. You can (and should) add specific catch statements for better error reporting.
Exceptions when multithreading
There are two basic ways of executing code asynchronously in C++11 using standard library features: std::async and std::thread.
First the simple one. std::async will return a std::future which will capture and store any uncaught exceptions thrown in the given function. Calling std::future::get on the future will cause any exceptions to propagate into the calling thread.
auto fut = std::async(std::launch::async, [] () { throw std::runtime_error {"oh dear"}; });
fut.get(); // fine, throws exception
On the other hand, if an exception in a std::thread object is uncaught then std::terminate will be called:
try {
std::thread t {[] () { throw std::runtime_error {"oh dear"};}};
t.join();
} catch(...) {
// only get here if std::thread constructor throws
}
One solution to this could be to pass a std::exception_ptr into the std::thread object which it can pass the exception to:
void foo(std::exception_ptr& eptr)
{
try {
throw std::runtime_error {"oh dear"};
} catch (...) {
eptr = std::current_exception();
}
}
void bar()
{
std::exception_ptr eptr {};
std::thread t {foo, std::ref(eptr)};
try {
// do stuff
} catch(...) {
t.join(); // t may also have thrown
throw;
}
t.join();
if (eptr) {
std::rethrow_exception(eptr);
}
}
Although a better way is to use std::package_task:
void foo()
{
throw std::runtime_error {"oh dear"};
}
void bar()
{
std::packaged_task<void()> task {foo};
auto fut = task.get_future();
std::thread t {std::move(task)};
t.join();
auto result = fut.get(); // throws here
}
But unless you have good reason to use std::thread, prefer std::async.
There's nothing wrong with catching unrecoverable errors and shutting down your program this way. In fact, it's how exceptions should be used. However, be careful not to cross the line of using exceptions to control the flow of your program in ordinary circumstances. They should always represent an error which cannot be gracefully handled at the level the error occurred.
Calling exit() would not unwind the stack from wherever you called it. If you want to exit cleanly, what you're already doing is ideal.
You have already accepted an answer, but I wanted to add something about this:
Can I just explicitly call something like exit() instead?
You can call exit, but (probably) shouldn't.
std::exit should be reserved for situations where you want to express "exit right now!", not simply "application has nothing left to do".
As an example, if you were to write a controller for a laser used in cancer treatments, your first priority in case something went wrong would be to shut down the laser and call std::exit - or possibly std::terminate (to ensure any side effects of a hanging, slow or crashing application do not kill a patient).
Similar to how exceptions should not be used for controlling application flow, exit should not be used to stop the application in normal conditions.
Is using exceptions the proper way to terminate my program if all I want is to display an error message and close (accounting that I may be deep in the program)?
Yes. This is the reason for using exceptions. An error occurred deep down in the code and something at a higher level will handle it. In your case, at the highest level.
There are arguments for/against exceptions vs. error codes, and this is a good read:
Exceptions or error codes
Can I just explicitly call something like exit() instead?
You can, but you may end up duplicating your logging code. Also, if in the future you decide that you want to handle an exception differently you will have to change all your exit calls. Imagine you wanted a different message, or to fall back on an alternative process.
Another similar question:
Correct usage of exit() in c++?
You also have a flaw in your approach as you don't handle all (C++) exceptions. You want something like this:
int main()
{
Game game;
try
{
game.run();
}
catch (BadResolutionException & e)
{
Notification::showErrorMessage(e.what(), "ERROR: Resolution");
return 1;
}
catch (BadAssetException & e)
{
Notification::showErrorMessage(e.what(), "ERROR: Assets");
return 1;
}
catch (std::bad_alloc & e)
{
Notification::showErrorMessage(e.what(), "ERROR: Memory");
return 1;
}
catch (...)
{
// overload?
Notification::showErrorMessage("ERROR: Unhandled");
return 1;
}
return 0;
}
If you don't handle all* exceptions you could have the game terminate without telling you anything useful.
You can't handle ALL exceptions. See this link:
C++ catching all exceptions
From the documentation:
[[noreturn]] void exit (int status);
Terminate calling process
Terminates the process normally, performing the regular cleanup for terminating programs.
Normal program termination performs the following (in the same order):
Objects associated with the current thread with thread storage duration are destroyed (C++11 only).
Objects with static storage duration are destroyed (C++) and functions registered with atexit are called.
All C streams (open with functions in ) are closed (and flushed, if buffered), and all files created with tmpfile are removed.
Control is returned to the host environment.
Note that objects with automatic storage are not destroyed by calling exit (C++).
If status is zero or EXIT_SUCCESS, a successful termination status is returned to the host environment.
If status is EXIT_FAILURE, an unsuccessful termination status is returned to the host environment.
Otherwise, the status returned depends on the system and library implementation.
For a similar function that does not perform the cleanup described above, see quick_exit.

How can I propagate exceptions between threads?

We have a function which a single thread calls into (we name this the main thread). Within the body of the function we spawn multiple worker threads to do CPU intensive work, wait for all threads to finish, then return the result on the main thread.
The result is that the caller can use the function naively, and internally it'll make use of multiple cores.
All good so far..
The problem we have is dealing with exceptions. We don't want exceptions on the worker threads to crash the application. We want the caller to the function to be able to catch them on the main thread. We must catch exceptions on the worker threads and propagate them across to the main thread to have them continue unwinding from there.
How can we do this?
The best I can think of is:
Catch a whole variety of exceptions on our worker threads (std::exception and a few of our own ones).
Record the type and message of the exception.
Have a corresponding switch statement on the main thread which rethrows exceptions of whatever type was recorded on the worker thread.
This has the obvious disadvantage of only supporting a limited set of exception types, and would need modification whenever new exception types were added.
C++11 introduced the exception_ptr type that allows to transport exceptions between threads:
#include<iostream>
#include<thread>
#include<exception>
#include<stdexcept>
static std::exception_ptr teptr = nullptr;
void f()
{
try
{
std::this_thread::sleep_for(std::chrono::seconds(1));
throw std::runtime_error("To be passed between threads");
}
catch(...)
{
teptr = std::current_exception();
}
}
int main(int argc, char **argv)
{
std::thread mythread(f);
mythread.join();
if (teptr) {
try{
std::rethrow_exception(teptr);
}
catch(const std::exception &ex)
{
std::cerr << "Thread exited with exception: " << ex.what() << "\n";
}
}
return 0;
}
Because in your case you have multiple worker threads, you will need to keep one exception_ptr for each of them.
Note that exception_ptr is a shared ptr-like pointer, so you will need to keep at least one exception_ptr pointing to each exception or they will be released.
Microsoft specific: if you use SEH Exceptions (/EHa), the example code will also transport SEH exceptions like access violations, which may not be what you want.
Currently, the only portable way is to write catch clauses for all the types of exceptions that you might like to transfer between threads, store the information somewhere from that catch clause and then use it later to rethrow an exception. This is the approach taken by Boost.Exception.
In C++0x, you will be able to catch an exception with catch(...) and then store it in an instance of std::exception_ptr using std::current_exception(). You can then rethrow it later from the same or a different thread with std::rethrow_exception().
If you are using Microsoft Visual Studio 2005 or later, then the just::thread C++0x thread library supports std::exception_ptr. (Disclaimer: this is my product).
If you're using C++11, then std::future might do exactly what you're looking for: it can automagically trap exceptions that make it to the top of the worker thread, and pass them through to the parent thread at the point that std::future::get is called. (Behind the scenes, this happens exactly as in #AnthonyWilliams' answer; it's just been implemented for you already.)
The down side is that there's no standard way to "stop caring about" a std::future; even its destructor will simply block until the task is done. [EDIT, 2017: The blocking-destructor behavior is a misfeature only of the pseudo-futures returned from std::async, which you should never use anyway. Normal futures don't block in their destructor. But you still can't "cancel" tasks if you're using std::future: the promise-fulfilling task(s) will continue running behind the scenes even if nobody is listening for the answer anymore.] Here's a toy example that might clarify what I mean:
#include <atomic>
#include <chrono>
#include <exception>
#include <future>
#include <thread>
#include <vector>
#include <stdio.h>
bool is_prime(int n)
{
if (n == 1010) {
puts("is_prime(1010) throws an exception");
throw std::logic_error("1010");
}
/* We actually want this loop to run slowly, for demonstration purposes. */
std::this_thread::sleep_for(std::chrono::milliseconds(100));
for (int i=2; i < n; ++i) { if (n % i == 0) return false; }
return (n >= 2);
}
int worker()
{
static std::atomic<int> hundreds(0);
const int start = 100 * hundreds++;
const int end = start + 100;
int sum = 0;
for (int i=start; i < end; ++i) {
if (is_prime(i)) { printf("%d is prime\n", i); sum += i; }
}
return sum;
}
int spawn_workers(int N)
{
std::vector<std::future<int>> waitables;
for (int i=0; i < N; ++i) {
std::future<int> f = std::async(std::launch::async, worker);
waitables.emplace_back(std::move(f));
}
int sum = 0;
for (std::future<int> &f : waitables) {
sum += f.get(); /* may throw an exception */
}
return sum;
/* But watch out! When f.get() throws an exception, we still need
* to unwind the stack, which means destructing "waitables" and each
* of its elements. The destructor of each std::future will block
* as if calling this->wait(). So in fact this may not do what you
* really want. */
}
int main()
{
try {
int sum = spawn_workers(100);
printf("sum is %d\n", sum);
} catch (std::exception &e) {
/* This line will be printed after all the prime-number output. */
printf("Caught %s\n", e.what());
}
}
I just tried to write a work-alike example using std::thread and std::exception_ptr, but something's going wrong with std::exception_ptr (using libc++) so I haven't gotten it to actually work yet. :(
[EDIT, 2017:
int main() {
std::exception_ptr e;
std::thread t1([&e](){
try {
::operator new(-1);
} catch (...) {
e = std::current_exception();
}
});
t1.join();
try {
std::rethrow_exception(e);
} catch (const std::bad_alloc&) {
puts("Success!");
}
}
I have no idea what I was doing wrong in 2013, but I'm sure it was my fault.]
You problem is that you could receive multiple exceptions, from multiple threads, as each could fail, perhaps from different reasons.
I am assuming the main thread is somehow waiting for the threads to end to retrieve the results, or checking regularly the other threads' progress, and that access to shared data is synchronized.
Simple solution
The simple solution would be to catch all exceptions in each thread, record them in a shared variable (in the main thread).
Once all threads finished, decide what to do with the exceptions. This means that all other threads continued their processing, which perhaps, is not what you want.
Complex solution
The more complex solution is have each of your threads check at strategic points of their execution, if an exception was thrown from another thread.
If a thread throws an exception, it is caught before exiting the thread, the exception object is copied into some container in the main thread (as in the simple solution), and some shared boolean variable is set to true.
And when another thread tests this boolean, it sees the execution is to be aborted, and aborts in a graceful way.
When all thread did abort, the main thread can handle the exception as needed.
An exception thrown from a thread will not be catchable in the parent thread. Threads have different contexts and stacks, and generally the parent thread is not required to stay there and wait for the children to finish, so that it could catch their exceptions. There is simply no place in code for that catch:
try
{
start thread();
wait_finish( thread );
}
catch(...)
{
// will catch exceptions generated within start and wait,
// but not from the thread itself
}
You will need to catch exceptions inside each thread and interpret exit status from threads in the main thread to re-throw any exceptions you might need.
BTW, in the absents of a catch in a thread it is implementation specific if stack unwinding will be done at all, i.e. your automatic variables' destructors may not even be called before terminate is called. Some compilers do that, but it's not required.
Could you serialize the exception in the worker thread, transmit that back to the main thread, deserialize, and throw it again? I expect that for this to work the exceptions would all have to derive from the same class (or at least a small set of classes with the switch statement thing again). Also, I'm not sure that they would be serializable, I'm just thinking out loud.
There is, indeed, no good and generic way to transmit exceptions from one thread to the next.
If, as it should, all your exceptions derive from std::exception, then you can have a top-level general exception catch that will somehow send the exception to the main thread where it will be thrown again. The problem being you loose the throwing point of the exception. You can probably write compiler-dependent code to get this information and transmit it though.
If not all your exception inherit std::exception, then you are in trouble and have to write a lot of top-level catch in your thread ... but the solution still hold.
You will need to do a generic catch for all exceptions in the worker (including non-std exceptions, like access violations), and send a message from the worker thread (i suppose you have some kind of messaging in place?) to the controlling thread, containing a live pointer to the exception, and rethrow there by creating a copy of the exception.
Then the worker can free the original object and exit.
See http://www.boost.org/doc/libs/release/libs/exception/doc/tutorial_exception_ptr.html. It is also possible to write a wrapper function of whatever function you call to join a child thread, which automatically re-throws (using boost::rethrow_exception) any exception emitted by a child thread.