Catching exceptions from threads

R

Ron James

In my multi-threaded application, a Win32 structured exception is
occasionally thrown from a worker thread. Or perhaps a worker thread might
throw a C++ exception. I can catch the Win32 structured exception in my
Main thread and take remedial action. However the C++ exception appears to
be handle by something (the CRT ?) which (a) pops up an unwanted dialog box
and (b) terminates my thread without my main thread ever getting to hear
about it.

I assume the CRT (or whatever) is deciding that I have an unhandled C++
exception and is "helping me out". Can I persuade the CRT somehow that I
want my main thread to catch a C++ exception which has been thrown in a
worker thread?

Obviously I can wrap each worker thread in a C++ try/catch block, but I'd
rather a more generic solution if one is available.

Many thanks
 
R

Ron James

Unfortunately, it's not quite that simple. This is an application that can
process thousands of transactions per minute, and I get exceptions a few
times a week.
 
C

Carl Daniel [VC++ MVP]

Ron said:
Obviously I can wrap each worker thread in a C++ try/catch block, but
I'd rather a more generic solution if one is available.

That's the correct solution. There's no way to catch an exception raised in
"Thread B" from within "Thread A".

-cd
 
W

William DePalo [MVP VC++]

Ron James said:
Obviously I can wrap each worker thread in a C++ try/catch block, but I'd
rather a more generic solution if one is available.

As Carl has already mentioned, C++ exception handlers are with respect to a
stack frame and thread.

However, if you target XP or 2K+3, and if your problem is due to a
structured exception (i.e. from Win32) then you can preempt the structured
execption handler by installing a vectored execption handler.

You might want to take a look at this article by Matt Pietrek:

http://msdn.microsoft.com/msdnmag/issues/01/09/hood/default.aspx

and the MSDN help entry for AddVectoredExceptionHandler().

I should point out, though, that I haven't ever tried to mix C++ exceptions
and vectored exception handling as mixing the frame based exceptions is
enough to cause me a headache. :)

Regards,
Will
 
B

Bill Kirtley

The C runtime library is responsible for displaying that
alert box. It can be configured to write to stdout rather
than displaying an alert by:

_set_error_mode(_OUT_TO_STDERR);


-Bill Kirtley
kirtley at envoyww.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top