zoukankan      html  css  js  c++  java
  • Windows Internals 笔记——错误处理

    1.Windows函数检测到错误时,会使用一种名为“线程本地存储区”的机制将相应的错误代码与“主调线程”关联到一起。这种机制使得不同的线程能独立运行,不会出现相互干扰对方的错误代码的情况。

    2.GetLastError返回32位的错误代码表,每个错误有三种表示:一个消息ID、消息文本、和一个编号。函数失败后应立即调用GetLastError,否则很可能被改写。

    //
    // MessageId: ERROR_SUCCESS
    //
    // MessageText:
    //
    // The operation completed successfully.
    //
    #define ERROR_SUCCESS                    0L
    
    #define NO_ERROR 0L                                                 // dderror
    #define SEC_E_OK                         ((HRESULT)0x00000000L)
    
    //
    // MessageId: ERROR_INVALID_FUNCTION
    //
    // MessageText:
    //
    // Incorrect function.
    //
    #define ERROR_INVALID_FUNCTION           1L    // dderror
    
    //
    // MessageId: ERROR_FILE_NOT_FOUND
    //
    // MessageText:
    //
    // The system cannot find the file specified.
    //
    #define ERROR_FILE_NOT_FOUND             2L


     

    3.可以用FormatMessage函数来格式化输出错误信息。

    void OutputLastError(LPTSTR lpszFunctionName)
    {
        LPVOID lpMsgBuf;
        LPVOID lpDisplayBuf;
        DWORD dwErrorCode = GetLastError();
    
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            dwErrorCode,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR)&lpMsgBuf,
            0, NULL);
    
        lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunctionName) + 40) * sizeof(TCHAR));
        StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d : %s"), lpszFunctionName, dwErrorCode, lpMsgBuf);
    
        _tprintf((LPCTSTR)lpDisplayBuf);
    
        LocalFree(lpMsgBuf);
        LocalFree(lpDisplayBuf);
    }


    4.我们可以使用 void SetLastError(DWORD dwErrCode); 来设置错误代码,也可以创建自己的代码,32位字段的组成如下:

    需要注意的是第29位。

  • 相关阅读:
    The kernel’s command-line parameters(1)
    Linux kernel release 5.x <http://kernel.org/>(1)
    2020 LInux Kernel History Report(2)
    2020 LInux Kernel History Report
    Android下拉刷新,上拉加载
    多条目加载和适配器
    PAT:1071. Speech Patterns (25) AC
    PAT:1054. The Dominant Color (20) AC(map法)
    PAT:1054. The Dominant Color (20) AC(抓住最多的特点,处理不同和相同的情况,留下剩余的答案)
    PAT:1060. Are They Equal (25) AC
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/8087453.html
Copyright © 2011-2022 走看看