这个系列是本人基于对比Linux程序设计的同时一并学习Windows的程序设计,在开始程序设计之前,我们第一件事情就是查看Windows是如何处理错误的,方便我们后续继续开展Windows程序设计的学习
目录
前言
第一件事情,我们使用的就是Windows提供的SDK,常见的函数的返回的数据类型有
-
VOID(不可能失败的函数,很少有函数的返回类型是VOID)
-
BOOL(函数失败返回0,反之返回的是一个非0的值,一个好的办法是检查这个函数的返回值是不是False来断言他是否失败!)
-
PVOID(函数调用失败返回NULL,否则会标识一块内存)
-
LONG/DWORD,这类函数请查看具体的SDK说明!
一个好的办法就是立马查看GetLastError返回最近的一次错误!
DWORD GetLastError();
有些令人难受的是:Windows的函数是首字母大写的,我们没办法依靠字母大小写断定他可能的类型
在WinError.h中,存在定义错误码的文件:近7w行的大文件!
// // 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 // ...
可以看到,每一个错误有三种标识:
-
消息ID(在源代码上使用的宏)
-
消息文本(描述错误)
-
一个标号(不必理会这个,不建议使用这个)
当我们调用GetLastError函数,返回的总是错误码,直接扔给用户看错误码多少不太友好,
DWORD FormatMessage( [in] DWORD dwFlags, [in, optional] LPCVOID lpSource, [in] DWORD dwMessageId, [in] DWORD dwLanguageId, [out] LPTSTR lpBuffer, [in] DWORD nSize, [in, optional] va_list *Arguments );
可以使用这个函数得到错误描述字符串。
定义属于我们自己的错误码
我们可以定义自己的错误码!很简单
VOID SetLastError(DWORD dwErrCode);
DWORD是一个32位的值,来看看你应该如何排布他!
// // Note: There is a slightly modified layout for HRESULT values below, // after the heading "COM Error Codes". // // Search for "**** Available SYSTEM error codes ****" to find where to // insert new error codes // // Values are 32 bit values laid out as follows: // // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 // +---+-+-+-----------------------+-------------------------------+ // |Sev|C|R| Facility | Code | // +---+-+-+-----------------------+-------------------------------+ // // where // // Sev - is the severity code // // 00 - Success // 01 - Informational // 10 - Warning // 11 - Error // // C - is the Customer code flag // // R - is a reserved bit // // Facility - is the facility code // // Code - is the facility's status code // // // Define the facility codes //
位 | 31-30 | 29 | 28 | 27-16 | 15-0 |
---|---|---|---|---|---|
内容 | 严重性 | Microsoft/客户 | 保留 | Facility代码 | 异常代码 |
含义 | 0 成功 1 信息(提示) 2 警告 3 错误 | 0:Microsoft定义 1:客户自定义 | 0 | 前256个值被Microsoft保留 | 定义的代码 |
Reference
GetLastError 函数 (errhandlingapi.h) - Win32 apps | Microsoft Learn