zoukankan      html  css  js  c++  java
  • Windows API 编程----将错误代码转换成错误描述信息

     

      Windows编程有时会因为调用函数而产生错误,调用GetLastError()函数可以得到错误代码。如果错误代码为0,说明没有错误;如果错误代码不为0,则说明存在错误。

      而错误代码不方便编程人员或用户直观理解到底发生了什么错误。Visual Studio 2015(或之前的版本)提供了“错误查找”的外部工具,输入错误代码即可以查看到底发生了什么错误。

      

      

      如果想在程序代码中查看错误代码对应的错误信息,可以编写如下函数来实现:

    #include<iostream>
    #include<Windows.h>
    using namespace std;
    void winerr( );
    
    int main(int argc, char* argv[])
    {
        system("haha");
        winerr();
        system("pause");
        return 0;
    }
    
    void winerr( )
    {
        char* win_msg = NULL;
        DWORD code = GetLastError();
        if (code == 0)
        {
            cout << "error "<<code<<":No error!
    ";
            return;
        }
            
        else
        {
            //获取错误信息
            FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&win_msg, 0, NULL);
            if (win_msg != NULL)
            {
                cout << "error " << code <<":" << win_msg << endl;
                LocalFree(win_msg);
            }
        }
        //为了使得该函数的调用不影响后续函数调用GetLastError()函数的结果
        SetLastError(code);
    }

    测试结果:

  • 相关阅读:
    js中定时器2
    js中定时器之一
    js中的Event对象
    hdu 1041(递推,大数)
    hdu 1130,hdu 1131(卡特兰数,大数)
    hdu 2044-2050 递推专题
    hdu 3078(LCA的在线算法)
    hdu 1806(线段树区间合并)
    hdu 3308(线段树区间合并)
    poj 2452(RMQ+二分查找)
  • 原文地址:https://www.cnblogs.com/dongling/p/5563288.html
Copyright © 2011-2022 走看看