3

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?

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
cheroky
  • 755
  • 1
  • 8
  • 16

2 Answers2

3

No you can`t.

A SEGFAULT isn't a regular exception.

The code you show is simply undefined behavior, and anything may be happen. There's no guarantee it ends up throwing an exception.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

This answer is very specific to WINDOWS.

You can use Structured Exception Handling.

You have to call "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.

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

Here is the list of exception records that you get in "PEXCEPTION_POINTERS". The first one is "EXCEPTION_ACCESS_VIOLATION" (in LINUX terms SEGFAULT)

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

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34