天天看點

捕獲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

繼續閱讀