天天看点

捕获Unhandled Exception-友好退出你的程序

在某些情况下,我们需要在程序发生未处理异常(unhandled exception)后主动退出,而不是等到程序崩溃(crash),这样可以保证发生崩溃的程序能够进行必要的挽救工作,比如重启进程或服务,或者将用户的崩溃信息(dump等)发送回来以解决此类问题。

实现的方法主要有两种:

1. 在程序的main函数或关键函数中,使用SEH(_try, _except)捕获所有的异常,在_except语句中做相应的操作后退出程序。

2.使用SetUnhandledExceptionFilter.缺点:调试器无法接收到2nd chance exception

code segment:

 int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])

{

int nRetCode = 0;

LPTOP_LEVEL_EXCEPTION_FILTER MyErrorFunc = MyUnhandledExceptionFilter;

::SetUnhandledExceptionFilter(MyErrorFunc);

//Function which will throw an exception

ThrowError();

return nRetCode;

}

LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS* ExceptionInfo)

{

PEXCEPTION_RECORD record = ExceptionInfo->ExceptionRecord;

CString strErrorRecord = NULL;

if(record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION )

strErrorRecord.Format(_T("Exception Access Violation: %x"),record->ExceptionAddress);

else

strErrorRecord.Format(_T("Exception Code:%x/nException Address:%x"),record->ExceptionCode,record->ExceptionAddress);

_tprintf(_T("%s"), strErrorRecord);

::MessageBox(NULL,strErrorRecord,_T("Exception"),MB_OK);

return EXCEPTION_EXECUTE_HANDLER;

}

you can find the definition of LPTOP_LEVEL_EXCEPTION_FILTER in winbase.h

继续阅读