VC++, .NET and unhandled exceptions

C

Colin Thomsen

I have a native VC++ application which runs differently
(incorrectly) if the .NET framework is installed.

A trimmed version of the app is shown below. The
intention is for the SEHHandler to catch any exceptions
which are not handled by the program. It is enabled using
the SetUnhandledExceptionFilter call.

The Pdh calls are intended to add a counter to enable
retrieval of CPU usage (not included in this trimmed
version)

The problem seems to be that after the call to
PdhAddCounter, the UnhandledExceptionFilter is reset. The
result is:
- without the call to PdhAddCounter, the program
prints 'Caught the exception OK'
- with the call to PdhAddCounter, the program quits with
a Windows dialog box

title: Microsoft Visual C++ Runtime Library
Message: Runtime Error!
Pogram: ...
This application has requested the Runtime to
terminate it in an unusual way. Please contact the
application's support team for more information.


This problem only occurs on computers with .NET installed.


#include <windows.h>
#include <stdexcept>
#include <pdh.h>
#include <tchar.h>
#include <iostream>

#define CNTR_CPU "\\Processor(_Total)\\% Processor
Time" // % of cpu in use

LONG __stdcall SEHHandler(EXCEPTION_POINTERS *pExPtrs)
{
std::cout << "Caught the exception OK" << std::endl;
return (EXCEPTION_EXECUTE_HANDLER);
}

void exceptionTest()
{
SetUnhandledExceptionFilter(SEHHandler);
static HQUERY h;
static HCOUNTER hcounter;
PdhOpenQuery (0, 0, &h) ;
PDH_STATUS pdhStatus = PdhAddCounter (h,_T(CNTR_CPU),
0, &hcounter);
PdhCloseQuery (h);
throw std::runtime_error("bad");
}

int main(int argc, char **argv)
{
exceptionTest();
return 0;
}

Any ideas?
 
C

Carl Daniel [VC++ MVP]

That repros for me too - no idea why though. I'll ask someone from MS to
take a look.

-cd
 
C

Carl Daniel [VC++ MVP]

I heard back from MS on this issue -

Apparently the phenomenon you're seeing is due to PDH DLL loading second
version of the CRT into the process, and the loading of the CRT causes the
unhandled exception filter to be reset. The variation in behavior from
machine to machine is reportedly due to different versions of PDH.DLL and/or
the CRT on those machines.

At present, it sounds like the only workaround is to be aware of the issue -
either make sure that PDH is loaded before you set the unhandled exception
filter, or call SetUnhandledExceptionFilter again after using PDH functions.

This should be addressed in a future release.

-cd
 

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