Windows编程 - 01 - 错误处理
时间:2010-09-09 来源:小风_ks
1. Windows函数返回类型
类型 |
错误的返回值 |
---|---|
VOID |
这种函数没有返回值,一般不出错 |
BOOL |
返回FALSE表示出错, FALSE为0, TRUE正确, TRUE为非0值 |
HANDLE |
出错返回NULL, 正确返回对象句柄, 注意HANDLE=INVALID_HANDLE_VALUE, which is defined as -1. |
PVOID |
NULL或者指向内存的指针 |
LONG/DWORD |
这个不同的函数有不同的意义,具体参考MSDN |
2. ErrorCode
类似标准C函数的extern int errno, Windows 也定义了一个全局的ErrorCode, 在Windows中可以通过GetLastError() 获得ErrorCode值
Windows通过一种 thread-local storage mechanism将ErrorCode与出错线程联系起来,(这个什么意思后现在不明白,后面讨论)
Error Code 都定义在WinErr.h头文件中, 每个errorcode都包含三项内容:MessageId, MessageText, MessageNumber
Error Code相关函数
DWORD GetLastError();
DWORD FormatMessage( DWORD dwFlags,LPCVOID pSource, DWORD dwMessageId,DWORD dwLanguageId, PTSTR pszBuffer, DWORD nSize,va_list *Arguments);
3. 调试时查看error code
在DEBUG->Watch窗口中, add Express "$err, hr", 就可以查看ErrorCode和 MessageText.
?加个图片在这里
4. 自定义ErrorCode
原则上尽量使用Windows的ErrorCode, 实在不能满足需要,可以自定义ErrorCode. 自定义ErrorCode只要选取一个合适的32bits值,然后调用void SetLastError(DWORD dwErrCd) 就成了。
选择ErrorCode值, 请看下表,目前这里只需要关心29bit 和 27-16 这两个地方。
Bits: |
31-30 |
29 |
28 |
27-16 |
15-0 |
---|---|---|---|---|---|
Contents |
Severity |
Microsoft/customer |
Reserved |
Facility code |
Exception code |
Meaning |
0=Success 1 = Informational 2 = Warning 3 = Error |
0 = Microsoft-defined code 1 = customer-defined code |
Must be 0 |
The first 256 values are reserved by Microsoft |
Microsoft/customer-defined code |
5. ErrorShow例子程序
??