How can a Windows application handle segmentation faults? By 'handle' I mean intercept them and perhaps output a descriptive message. Also, the ability to recover from them would be nice too, but I assume that is too complicated.
Let them crash and let the Windows Error Reporting handle it - under Vista+, you should also consider registering with Restart Manager, so that you have a chance to save out the user's work and restart the application (like what Word/Excel/etc.. does)
Use SEH for early exception handling, and use SetUnhandledExceptionFilter to show a descriptive message.
What you want to do here depends on what sort of faults you are concerned with. If you have sloppy code that is prone to more or less random General Protection Violations, then @Paul Betts answer is what you need.
If you have code that has a good reason to deference bad pointers, and you want to recover, start from @whunmr's suggestion about SEH. You can handle and indeed recover, if you have clear enough control of your code to know exactly what state it is in at the point of the fault and how to go about recovering.
If you add the /EHa
compiler argument then try {} catch(...)
will catch all exceptions for you, including SEH exceptions.
You can also use __try {} __except {}
which gives you more flexibility on what to do when an exception is caught. putting an __try {} __except {}
on your entire main()
function is somewhat equivalent to using SetUnhandeledExceptionFilter()
.
That being said, you should also use the proper terminology. "seg-fault" is a UNIX term. there are no segmentation faults on windows. On windows they are called "Access Violation exceopnts"