通过C++的try和catch来捕获SEH异常

本文介绍了如何在C++中通过try-catch结构捕获结构化异常(SEH)。当try-catch无法捕获所有异常时,作者提供了一个SException类,将结构化异常转换为C++异常。同时,文章提到了设置未处理异常过滤器(SetUnhandledExceptionFilter)以在程序异常未处理时生成DUMP文件,以便于后续调试。

在初学VC的时候,总以为try()catch(...)可以抓到所有的异常. 在开发之前开发的一个服务器程序中,才发现服务器经常莫名其妙的宕机了.一直觉得很诡异.

   直到后来看了很多资料才明白结构化异常跟C++异常是两套东西,不统一。有些异常try.catch不一定能不抓到. 要将两种异常共同使用.下面的代码可以达到目的. 使用下面异常类,可以使程序更稳定.(注意:编译选项里面要记得打开 结构化异常开关. compile with: /EHa)

[cpp]  view plain copy
  1. // 把结构化异常转化为C++异常  
  2.   
  3. struct SException  
  4.   
  5. {  
  6.   
  7.      EXCEPTION_RECORD er;  
  8.   
  9.      CONTEXT            context;  
  10.   
  11.      SException(PEXCEPTION_POINTERS pep)  
  12.   
  13.      {  
  14.   
  15.          er       = *(pep->ExceptionRecord);  
  16.   
  17.          context = *(pep->ContextRecord);  
  18.   
  19.      }  
  20.   
  21.      operator DWORD() { return er.ExceptionCode; }  
  22.   
  23.      static void MapSEtoCE() { _set_se_translator( TranslateSEToCE ); }  
  24.   
  25.   
  26.      static void __cdecl TranslateSEToCE( UINT dwEC, PEXCEPTION_POINTERS pep )  
  27.   
  28.      {  
  29.   
  30.          throw SException(pep);  
  31.   
  32.      }  
  33.   
  34. };  
  35.   
  36. void main()  
  37.   
  38. {  
  39.   
  40.      SException::MapSEtoCE();  
  41.   
  42.      try   
  43.   
  44.      {   
  45.   
  46.          int* p = 0;  
  47.   
  48.          int a = *p;  
  49.   
  50.      }  
  51.   
  52.      catch( SException& e )  
  53.   
  54.      {  
  55.   
  56.          if ( (DWORD)e == EXCEPTION_ACCESS_VIOLATION )  
  57.   
  58.          {  
  59.   
  60.               printf( "Access violation" );  
  61.   
  62.          }  
  63.   
  64.      }  
  65.   
  66. }  

 

另外可以调用MS提供的函数SetUnhandledExceptionFilter, 这是程序异常未处理的最后一到防线.可以在回调函数中写出DUMP文件,然后通过PDB文件来调试看到宕机的源代码段.

[cpp]  view plain copy
  1. LONG __stdcall MyCrashHandlerExceptionFilter(EXCEPTION_POINTERS* pEx)   
  2. {     
  3. #ifdef _M_IX86   
  4.     if (pEx->ExceptionRecord->ExceptionCode == EXCEPTION_STACK_OVERFLOW)     
  5.     {   
  6.         // be sure that we have enought space...   
  7.         static char MyStack[1024*128];     
  8.         // it assumes that DS and SS are the same!!! (this is the case for Win32)   
  9.         // change the stack only if the selectors are the same (this is the case for Win32)   
  10.         //__asm push offset MyStack[1024*128];   
  11.         //__asm pop esp;   
  12.         __asm mov eax,offset MyStack[1024*128];   
  13.         __asm mov esp,eax;   
  14.     }   
  15. #endif   
  16.   
  17.     bool bFailed = true;   
  18.     HANDLE hFile;   
  19.     hFile = CreateFile(szMiniDumpFileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);   
  20.     if (hFile != INVALID_HANDLE_VALUE)   
  21.     {   
  22.         MINIDUMP_EXCEPTION_INFORMATION stMDEI;   
  23.         stMDEI.ThreadId = GetCurrentThreadId();   
  24.         stMDEI.ExceptionPointers = pEx;   
  25.         stMDEI.ClientPointers = TRUE;   
  26.         // try to create an miniDump:   
  27.         if (s_pMDWD(   
  28.             GetCurrentProcess(),   
  29.             GetCurrentProcessId(),   
  30.             hFile,   
  31.             MiniDumpNormal,   
  32.             &stMDEI,   
  33.             NULL,   
  34.             NULL   
  35.             ))   
  36.         {   
  37.             bFailed = false;  // suceeded   
  38.         }   
  39.         CloseHandle(hFile);   
  40.     }   
  41.   
  42.     if (bFailed)   
  43.     {   
  44.         return EXCEPTION_CONTINUE_SEARCH;   
  45.     }     
  46.     if (bMsgbox)  
  47.     {  
  48.         string strMsg = "Run failed, Please Copy the ";  
  49.         strMsg += szMiniDumpFileName;  
  50.         strMsg += " file to us!";  
  51.   
  52.         ::MessageBox(NULL, strMsg.c_str(), TEXT("Error"), 0);  
  53.     }  
  54.       
  55.   
  56.     // or return one of the following:   
  57.     // - EXCEPTION_CONTINUE_SEARCH   
  58.     // - EXCEPTION_CONTINUE_EXECUTION   
  59.     // - EXCEPTION_EXECUTE_HANDLER   
  60.     return EXCEPTION_EXECUTE_HANDLER;  // this will trigger the "normal" OS error-dialog   
  61. }    
  62. #ifndef _M_IX86  
  63. #error "The following code only works for x86!"  
  64. #endif  
  65. LPTOP_LEVEL_EXCEPTION_FILTER WINAPI MyDummySetUnhandledExceptionFilter(  
  66.     LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter)  
  67. {  
  68.     return NULL;  
  69. }  
  70.   
  71. BOOL PreventSetUnhandledExceptionFilter()  
  72. {  
  73.     HMODULE hKernel32 = LoadLibrary(_T("kernel32.dll"));  
  74.     if (hKernel32 == NULL) return FALSE;  
  75.     void *pOrgEntry = GetProcAddress(hKernel32, "SetUnhandledExceptionFilter");  
  76.     if(pOrgEntry == NULL) return FALSE;  
  77.     unsigned char newJump[ 100 ];  
  78.     DWORD dwOrgEntryAddr = (DWORD) pOrgEntry;  
  79.     dwOrgEntryAddr += 5; // add 5 for 5 op-codes for jmp far  
  80.     void *pNewFunc = &MyDummySetUnhandledExceptionFilter;  
  81.     DWORD dwNewEntryAddr = (DWORD) pNewFunc;  
  82.     DWORD dwRelativeAddr = dwNewEntryAddr-dwOrgEntryAddr;  
  83.   
  84.     newJump[ 0 ] = 0xE9;  // JMP absolute  
  85.     memcpy(&newJump[ 1 ], &dwRelativeAddr, sizeof(pNewFunc));  
  86.     SIZE_T bytesWritten;  
  87.     BOOL bRet = WriteProcessMemory(GetCurrentProcess(),  
  88.         pOrgEntry, newJump, sizeof(pNewFunc) + 1, &bytesWritten);  
  89.     return bRet;  
  90. }   
  91.   
  92. void InitMiniDumpWriter()   
  93. {   
  94.     if (s_hDbgHelpMod != NULL)   
  95.         return;   
  96.   
  97.     // Initialize the member, so we do not load the dll after the exception has occured   
  98.     // which might be not possible anymore...   
  99.     s_hDbgHelpMod = LoadLibrary(_T("dbghelp.dll"));   
  100.     if (s_hDbgHelpMod != NULL)   
  101.         s_pMDWD = (tMDWD) GetProcAddress(s_hDbgHelpMod, "MiniDumpWriteDump");   
  102.   
  103.     // Register Unhandled Exception-Filter:   
  104.     LPTOP_LEVEL_EXCEPTION_FILTER p = SetUnhandledExceptionFilter(MyCrashHandlerExceptionFilter);    
  105.   
  106.     BOOL bRet = PreventSetUnhandledExceptionFilter();  
  107.   
  108.     // Additional call "PreventSetUnhandledExceptionFilter"...   
  109.     // See also: "SetUnhandledExceptionFilter" and VC8 (and later)   
  110.     // http://blog.kalmbachnet.de/?postid=75   
  111. }   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值