我有一个 CExceptionHandler
类,只要我的应用程序检测到运行时异常就会调用它。例如:
if ( val == NULL )
{
TRACE(_T("Unexpected NULL in sequence."));
AfxThrowException( ERROR_INVALID_DATA );
}
AfxThrowException
非常简单:
void AfxThrowException( DWORD error )
{
CExceptionHandler * pException = NULL;
if ( error == 0 )
{
error = ::GetLastError();
}
pException = new CExceptionHandler( error );
TRACE(_T("Warning: throwing CSerialException for error %d\n"), error);
THROW(pException);
}
这是CExceptionHandler
的成员Dump
函数:
void CExceptionHandler::Dump( CDumpContext & dc ) const
{
CObject::Dump(dc);
dc << "m_dwError = " << m_dwError;
}
在我的代码中,我有 try
/catch
语句:
try
{
/* My app does stuff where the exception is thrown. */
}
catch( CExceptionHandler * ex )
{
afxDump << _T("Dumping exceptional data: ") << _T("\r\n");
ex->Dump( afxDump );
afxDump << _T("\r\n");
}
我希望将收集到的调试信息转储到控制台。但是,当 PC 进入 catch
语句(使用断点验证)时,控制台上没有任何反应。我在 Debug模式下使用 Visual Studio 2008。想法表示赞赏。谢谢。
最佳答案
CDumpContext
将输出发送到调试器,而不是控制台(更多信息请参见 OutputDebugString
),如果您在 Visual Studio 调试器下运行,输出将出现在 输出窗口。
如果您还想将输出发送到控制台,您可以配置 CDumpContext
通过传递指向 CFile
的指针来写入 CFile
> CDumpContext
constructor 中的对象.
如果您的应用程序是使用“使用多字节字符集”配置选项构建的,您可以使用 CStdioFile
写入标准输出或标准错误:
CStdioFile file(stdout);
CDumpContext dumpContext(&file);
ex->Dump(dumpContext);
或者,如果你想使用afxDump
,你可以直接设置它的m_pFile
成员变量(它声明为public
)。例如,您可以将此代码放入 main
函数中:
CStdioFile file(stdout);
afxDump.m_pFile = &file;
但是,如果您的应用程序构建为 Unicode,这将不起作用,因为字符串需要转换为多字节才能写入标准输出。要进行转换,请编写一个继承 CFile
的类:
class CDumpFile : public CFile
{
public:
virtual void Write(const void* lpBuf, UINT nCount);
};
void CDumpFile::Write(const void* lpBuf, UINT nCount)
{
// Construct string from array of wide chars
const wchar_t* p = static_cast<const wchar_t*>(lpBuf);
UINT len = nCount / sizeof(wchar_t);
CStringW str(p, len);
CStringA astr(str); // Convert wide char to multibyte
fputs((LPCSTR)astr, stdout); // Write multibyte string to stdout
}
并像这样使用它:
CDumpFile file;
afxDump.m_pFile = &file;
关于您的代码的其他几点:
您应该确保在
catch
block 中删除异常对象。如果您的CExceptionHandler
类继承了 MFC 的CException
,那么您应该调用ex->Delete()
。如果没有,您需要删除 ex
。我建议不要为自己的函数使用
Afx
前缀 - 在我看来,您应该考虑将其保留供 MFC 库使用。
希望对您有所帮助!
关于c++ - 在捕获到异常时将有用的数据转储到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139448/