【问题标题】:Handling Exception in MFC在 MFC 中处理异常
【发布时间】:2010-09-23 16:59:54
【问题描述】:

我在我的程序中遇到了这个异常:

在 0x0051cce0 处未处理的异常 JSONDataParsing.exe:0xC0000005: 访问冲突读取位置 0x00000004

.

我尝试捕获异常,但没有用。我知道问题出在哪里。但想知道如何捕获异常。我在发生异常的代码周围使用了 try、catch 块。

这是一个无法捕获的异常吗?

catch 语句是:

catch (bad_alloc&)
        {
            TCHAR msgbuf[MAX_PATH];

            swprintf(msgbuf, L"bad_alloc \n");

            OutputDebugString(msgbuf);
        }
        catch (bad_cast&)
        {
            TCHAR msgbuf[MAX_PATH];

            swprintf(msgbuf, L"bad_cast \n");

            OutputDebugString(msgbuf);
        }
        catch (bad_exception&)
        {
            TCHAR msgbuf[MAX_PATH];

            swprintf(msgbuf, L"babad_exceptiond_alloc \n");

            OutputDebugString(msgbuf);
        }
        catch (bad_typeid&)
        {
            TCHAR msgbuf[MAX_PATH];

            swprintf(msgbuf, L"bad_alloc \n");

            OutputDebugString(msgbuf);
        }
        catch( CMemoryException* e )
        {

            TCHAR msgbuf[MAX_PATH];

            swprintf(msgbuf, L"CMemoryException \n");

            OutputDebugString(msgbuf);
            // Handle the out-of-memory exception here.
        }


        catch( CFileException* e )
        {

            TCHAR msgbuf[MAX_PATH];

            swprintf(msgbuf, L"CFileException \n");

            OutputDebugString(msgbuf);
            // Handle the file exceptions here.
        }

        catch( CException* e )
        {

            TCHAR msgbuf[MAX_PATH];

            swprintf(msgbuf, L"CException \n");

            OutputDebugString(msgbuf);
            // Handle the exception here.
            // "e" contains information about the exception.
            e->Delete();
        }

【问题讨论】:

标签: mfc exception-handling


【解决方案1】:

您只能使用特殊的 try-catch 处理程序捕获此类异常:

try
{
  // code that triggers such an exception. for example:
  int * a = NULL;
  *a = 0;
}
catch (...)
{
  // now that exception is handled here
}

但一般来说,这样做是不好的做法。相反,您不应该遇到这样的异常,而是检查您的参数和变量。

更多详情请看这里: http://members.cox.net/doug_web/eh.htm

【讨论】:

  • 嗨 Stefan,我使用了这个,但无法捕获访问冲突。
  • 你必须使用 /EHa 标志编译
【解决方案2】:

这种类型的低级异常可以使用 __try -except 语句捕获,但您应该修复它的原因而不是报告它。在 VS 中,在调试时按 CTRL+ALT+E 并检查那里的所有异常,然后继续运行您的应用程序,直到发生异常。提示将在有问题的行上停止。 看 http://msdn.microsoft.com/en-us/library/s58ftw19.aspx 了解详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2011-05-26
    相关资源
    最近更新 更多