freeeyes 发表于 2011-2-10 15:41:09

一个支持自动抛出异常的宏

写了一个简单的错误捕捉的宏。用于简单的错误排查,这个类会自动输出当前出错的文件名,函数名,感觉在DEBUG的时候挺有用的。在这里记录一下,很简单的一个.h,使用很简单。windows和linux下都能运行。
建立一个define.h
#ifndef _DEFIINE_H
#define _DEFIINE_H

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <time.h>

#define SHOW_PRINT    1
#define SHOW_WRITELOG 2

//nType = 1为显示在桌面上,2为记录为日志
void __show__(const char* pMsg, int nType)
{
      if(nType == 1)
      {
                printf("%s", pMsg);
      }

      if(nType == 2)
      {
                FILE* pFile = fopen("assert.log", "a");
                if(pFile != NULL)
                {
                        fwrite(pMsg, 1, strlen(pMsg), pFile);
                        fwrite("\r\n", 1, 2, pFile);
                        fclose(pFile);
                }
                else
                {
                        printf("file open Error(%s).\n", strerror(errno));
                }
      }
}

void sprintf_safe(char* szText, int nLen, char* fmt ...)
{
      if(szText == NULL)
      {
                return;
      }

      va_list ap;
      va_start(ap, fmt);
      vsnprintf(szText, nLen, fmt, ap);
      va_end(ap);
}

void __assertspecial__(const char* pFile, int nLen, const char* pFuncName, const char* pExpr, const char* pMsg)
{
      char szTemp = {'\0'};
      char szDate = {'\0'};

      struct tm *local;
      time_t t;
      t = time(NULL);
      local = localtime(&t);
      sprintf_safe(szDate, 50, "%04d-%02d-%02d %02d:%02d:%02d", local->tm_year + 1900, local->tm_mon + 1, local->tm_mday, local->tm_hour, local->tm_min, local->tm_sec);

      sprintf_safe(szTemp, 1024, "[%s](%s)(%d)(%s)(%s)(%s)\n", szDate, pFile, nLen, pFuncName, pExpr, pMsg);

      __show__(szTemp, SHOW_WRITELOG);
}

#ifdef WIN32
      #define AssertSpecial(type, msg) {if(type == false) { __assertspecial__(__FILE__, __LINE__, __FUNCTION__, #type, msg);} }
#else
      #define AssertSpecial(type, msg) {if(type == false) { __assertspecial__(__FILE__, __LINE__, __PRETTY_FUNCTION__, #type, msg);} }
#endif

#define _ENTER_FUNCTION {try{

#ifdef WIN32
      #define _LEAVE_FUNCTION }catch(...) { AssertSpecial(false, __FUNCTION__); }}
#else
      #define _LEAVE_FUNCTION }catch(...) { AssertSpecial(false, __PRETTY_FUNCTION__); }}
#endif

#endif



测试一下:
int main(int argc, char* argv[])
{

printf("Begin.\n");

_ENTER_FUNCTION


throw 1;


_LEAVE_FUNCTION

return 0;
}


输出日志:
(testerror.cpp)(14)(main)(false)(main)

其实这个可以稍微再改一下,支持一下msg,不过对于不复杂的错误检测,差不多够了,有助于查错。
页: [1]
查看完整版本: 一个支持自动抛出异常的宏