C++ 在捕获异常时将有用数据转储到控制台
我有一个C++ 在捕获异常时将有用数据转储到控制台,c++,visual-studio-2008,mfc,exception-handling,console-application,C++,Visual Studio 2008,Mfc,Exception Handling,Console Application,我有一个CExceptionHandler类,每当我的应用程序检测到运行时异常时就会调用它。例如: if ( val == NULL ) { TRACE(_T("Unexpected NULL in sequence.")); AfxThrowException( ERROR_INVALID_DATA ); } AfxThrowException非常简单: void AfxThrowException( DWORD error ) { CExceptionHandler
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;
}
我希望收集的调试信息被转储到控制台。但是,当PC进入
catch
语句(通过断点验证)时,控制台上不会发生任何事情。我正在调试模式下使用VisualStudio2008。思想是值得赞赏的。谢谢。CDumpContext
将输出发送到调试器,而不是控制台(有关详细信息,请参阅),如果在Visual Studio调试器下运行,输出将显示在输出窗口中
如果还希望将输出发送到控制台,则可以配置CDumpContext
,通过在中传递指向CFile
对象的指针来写入CFile
如果应用程序是使用“使用多字节字符集”配置选项构建的,则可以使用来写入stdout或stderr:
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
}
关于您的代码,还有几点:
catch
块中删除异常对象。如果您的CExceptionHandler
类继承了MFC的CException
,那么您应该调用ex->Delete()。如果没有,您需要删除ex
我希望这有帮助 您是否会抛出动态分配的内存?@GMan:你用“原因”而不是“结果”有结果吗<代码>:)(哦,我想这对你来说是MFC。但我对这件事的看法只是道听途说…)控制台?这是MFC,不是吗?尝试输出窗口。@Hans Passant:
CExceptionHandler
是MFC(.dll),但应用程序(.exe)不是(Win32控制台项目)。嗨,Jim,我已经根据您的评论更新了我的答案。谢谢!我使用CDumpContext-dumpContext(&file)
实现了这个解决方案,它在大部分情况下都能正常工作。但是,它将字符隔开(a C E x C E p t i o n H a n d l E r a t$0 E 2 4 E 4 0 m ud w E r o r=1 7 0
。有没有想到是什么原因造成的?是的,这是因为CStdioFile
正在将wchar_t
字符串写入控制台,而控制台需要MBCS。请参阅我更新的答案。
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;