_set_invalid_parameter_handler異常處理函數

VS2005以後的版本,微軟增長了一些新的異常機制,新機制在出現錯誤時默認不通知應用程序,這時程序就崩潰了。
因此這種狀況下,必須調用_set_invalid_parameter_handler、_set_purecall_handler設置本身的異常處理函數。express

如下示例代碼:函數

// test.cpp
// compile with: /Zi /MTd
// C++ Exceptions : /EHaui

#include <stdio.h>
#include <stdlib.h>指針

void myInvalidParameterHandler(const wchar_t* expression,
          const wchar_t* function, 
          const wchar_t* file, 
          unsigned int line, 
          uintptr_t pReserved)
{
 // function、file、line在Release下無效
 wprintf(L"Invalid parameter detected in function %s."
  L" File: %s Line: %d\n", function, file, line);
 wprintf(L"Expression: %s\n", expression);
 // 必須拋出異常,不然沒法定位錯誤位置
 throw 1;
}
void myPurecallHandler(void)
{
 printf("In _purecall_handler.");
 // 必須拋出異常,不然沒法定位錯誤位置
 throw 1;
}orm

int main()
{
 char* formatString;
 _invalid_parameter_handler oldHandler;
 _purecall_handler old_pure_handle;get

 oldHandler = _set_invalid_parameter_handler(myInvalidParameterHandler);
 old_pure_handle = _set_purecall_handler(myPurecallHandler);it

 try
 {
  formatString = NULL;
  printf(formatString);  // 發生異常
 }
 catch(...)
 {
  // 定位錯誤位置,輸出log
  printf("catch");
 }io

 getchar();
}function

說明:
一、因爲formatString是空指針,printf(formatString)發生異常,這時CRT會調用myInvalidParameterHandler進行處理;
二、myInvalidParameterHandler拋出異常。注意,function、file、line在Release下無效,因此必須拋出異常,不然沒法定位錯誤代碼;
三、設置工程選項C++ Exceptions : /EHa,讓catch抓住myInvalidParameterHandler拋出的異常,再作相應的處理;form

注意:若是myInvalidParameterHandler不拋出異常,那程序會往下執行,那麼可能會發生更糟糕的狀況。所以,建議拋出異常,停止執行後續的代碼。

相關文章
相關標籤/搜索