c++ - 在捕获到异常时将有用的数据转储到控制台

标签 c++ visual-studio-2008 mfc exception console-application

我有一个 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;

关于您的代码的其他几点:

  1. 您应该确保在 catch block 中删除异常对象。如果您的 CExceptionHandler 类继承了 MFC 的 CException,那么您应该调用 ex->Delete()。如果没有,您需要删除 ex

  2. 我建议不要为自己的函数使用 Afx 前缀 - 在我看来,您应该考虑将其保留供 MFC 库使用。

希望对您有所帮助!

关于c++ - 在捕获到异常时将有用的数据转储到控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139448/

相关文章:

mfc - 我可以取消特定的 C6031 警告吗? CString::LoadString

c++ - 在 C++ MFC 中使用 EnableMDITabbedGroups 时如何保留文档 Tab 键顺序

C++——OpenProcess 返回错误代码 87

c++ - C++11 : is there a simple way to seed the generator in one place of the code, 中的随机数然后在不同的函数中使用它?

c++ - 如何从 C++ 中的可变参数模板类派生

c++ - 避免进入 Visual Studio 2008 调试器中的 c++ std 头文件

c++ - 将一个元素从 vector 复制到另一 vector

visual-studio - 我可以在Visual Studio项目模板中创建 "Solution"级别的项目吗?

c# - 最小化 FormClose 防止计算机关机

c# - 寻找有关创建 C++ DLL 然后在 C# 中进行 P/Invoke 的代码示例(适用于 Windows CE 5/6)