简体   繁体   English

是否有可能通过try / catch捕获段错误?

[英]Is it possible to catch a segfault with try/catch?

I did this test to see what happened: 我做了这个测试,看看发生了什么:

try
{
    int *x = 0;
    *x = 1234;
}
catch(...)
{
    cout << "OK";
}

But it throws a segfault, why does it not catch the segfault? 但是它引发了一个段错误,为什么它不会遇到段错误呢?

No you can`t. 不,你不能。

A SEGFAULT isn't a regular exception. SEGFAULT不是常规异常。

The code you show is simply undefined behavior, and anything may be happen. 您展示的代码只是未定义的行为,任何事情都可能发生。 There's no guarantee it ends up throwing an exception. 无法保证最终会抛出异常。

This answer is very specific to WINDOWS. 这个答案对WINDOWS非常具体。

You can use Structured Exception Handling. 您可以使用结构化异常处理。

You have to call "SetUnhandledExceptionFilter" https://msdn.microsoft.com/en-us/library/ms680634(v=vs.85).aspx 你必须调用“SetUnhandledExceptionFilter” https://msdn.microsoft.com/en-us/library/ms680634(v=vs.85).aspx

usage prototype: 用法原型:

You have to register a function at the beginning of application 您必须在应用程序开始时注册一个函数

SetUnhandledExceptionFilter(UnhandledExceptionFilterFunction);

Define your registered function, Handle your business. 定义您的注册功能,处理您的业务。 Usually people collect coredumps and send Emails to dev team. 通常人们会收集coredump并将电子邮件发送给开发团队。

LONG WINAPI UnhandledExceptionFilterFunction(PEXCEPTION_POINTERS exception)
{


// The exception information is available in  PEXCEPTION_POINTERS 

}

Refer below link for PEXCEPTION_POINTERS https://msdn.microsoft.com/en-us/library/windows/desktop/ms679331(v=vs.85).aspx 请参阅以下链接PEXCEPTION_POINTERS https://msdn.microsoft.com/en-us/library/windows/desktop/ms679331(v=vs.85).aspx

Here is the list of exception records that you get in "PEXCEPTION_POINTERS". 以下是“PEXCEPTION_POINTERS”中的异常记录列表。 The first one is "EXCEPTION_ACCESS_VIOLATION" (in LINUX terms SEGFAULT) 第一个是“EXCEPTION_ACCESS_VIOLATION”(以LINUX术语SEGFAULT)

https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM