如何在WinCE中捕获未处理的异常?

时间:2013-12-11 06:03:47

标签: c++ exception-handling windows-ce

在桌面Windows中,我可以使用SetUnhandledExceptionFilter中的windows.h功能,但它在WinCE中不起作用。如何在WinCE中捕获未处理的异常?

注意:我使用的是C ++,而不是.NET。

1 个答案:

答案 0 :(得分:2)

到目前为止,我找到的唯一方法是使用以下命令包装应用程序中每个线程的执行:

__try
{
    // Call the thread start function here
}
__except(MyExceptionFilter(GetExceptionInformation())
{
    // Handle the exception here
}

这听起来像很多工作,但是如果你像这样编写一个为你包装线程的函数,它会变得相对简单:

typedef struct {
    void* startFct;
    void* args;
} ThreadHookArgs;

// "params" contains an heap-allocated instance of ThreadHookArgs
// with the wrapped thread start function and its arguments.
DWORD WINAPI wrapThread(LPVOID params) {

    ThreadHookArgs threadParams;
    memcpy(&args, params, sizeof(ThreadHookArgs));

    // Delete the parameters, now we have a copy of them
    delete params;

    __try {
        // Execute the thread start function
        return ((LPTHREAD_START_ROUTINE) threadParams.startFct) (threadParams.args);
    }
    __except(MyExceptionFilter(GetExceptionInformation())
    {
        // Handle the exception here
        return EXIT_FAILURE;
    }

}

然后编写自己的线程创建函数来调用钩子而不是线程启动函数:

// Drop-in replacement for CreateThread(), executes the given
// start function in a SEH exception handler
HANDLE MyCreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes,
                       DWORD dwStackSize,
                       LPTHREAD_START_ROUTINE lpStartAddress,
                       LPVOID lpParameter,
                       DWORD dwCreationFlags,
                       LPDWORD lpThreadId)
{
    HANDLE hThread;
    DWORD dwThreadId;

    LPTHREAD_START_ROUTINE startFct = lpStartAddress;
    LPVOID startParam = lpParameter;

    // Allocate the hook function arguments on the heap.
    // The function will delete them when it runs.
    ThreadHookArgs* hookArgs = new ThreadHookArgs;
    hookArgs->fct = lpStartAddress;
    hookArgs->args = lpParameter;

    // Set the start function of the created thread to
    // our exception handler hook function
    startFct = (LPTHREAD_START_ROUTINE) &wrapThread;
    startParam = hookArgs;

    // Start the hook function, which will in turn execute
    // the desired thread start function
    hThread = CreateThread( lpThreadAttributes,
                            dwStackSize,
                            startFct,
                            startParam,
                            dwCreationFlags,
                            &dwThreadId );

    return hThread;
}

请注意,如果您使用的是Windows CE 6及更高版本,那么这些版本都会进行矢量异常处理,这可能会让您更轻松:

http://msdn.microsoft.com/en-us/library/ee488606%28v=winembedded.60%29.aspx