您的位置:首页 > 其它

com 返回值检验及异常处理

2009-09-10 10:13 120 查看
该文算是我对com异常的一点总结。

ms定义的com 返回值hresult的结构

//
// Values are 32 bit values layed 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
//
//

可以通过下述方式检验返回值

SUCEED();FAILD();

打印错误:

WCHAR * GetErrorMessage(WCHAR *szBuffer, DWORD dwSize)
{
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
szBuffer,
dwSize - 1,
NULL
);
return szBuffer;
}

或者

WCHAR * GetErrorMessage(WCHAR *szBuffer, DWORD dwSize,HRESULT hr)
{
FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
hr,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
szBuffer,
dwSize - 1,
NULL
);
return szBuffer;
}

对于异常的处理:

try{....}

catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format(:%s/r/n%s",e.ErrorMessage(),(char*)e.Description());
AfxMessageBox(errormessage);///显示错误信息

return FALSE;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐