To check if it is possible I did the following:
try
{
int *x = 0;
*x = 1234;
}
catch(...)
{
cout << "OK";
}
But when I run it, I still get a segfault. I've read on some sites that try/catch can't catch a segfault, but I don't know if that's true, could someone please confirm that for me.
In any language, exceptions are not generated spontaneously, but it is the code itself that is responsible for throwing them.
Thus, for example,
new
it throws an exception when the requested reservation cannot be made. Simplifying a lot, this would be a possible example of implementation ofnew
:In the case of the example that you have given, access to an uninitialized pointer does not call any element of the standard library that can generate exceptions. This is where the operating system comes into play. Modern Operating Systems are able to monitor memory access and throw errors when trying to access memory for which there is no access. Since the responsibility for causing a failure lies with the Operating System, the solution to apply to control these accesses depends on the Operating System on which the application is going to run.
__try
and__except
. More information hereWindows example:
SIGSEV example:
All the best.
No, a segmentation fault is a signal, not an exception. Exceptions are manually thrown by the program (either you or a library), while signals are generated by the operating system (
SIGSEGV
,SIGABRT
,SIGKILL
, etc ).Exceptions are caught with
try
/ blockscatch
, and signals withsignal handlers
.Signals cannot be treated as exceptions because exceptions are thrown on a specific line of the program (where you put
throw
), while signals can appear at any time (since they are like interrupts, for example the user pressing Ctrl-C also generates a signal,SIGINT
).Exception handling involves adding, by the compiler, some control code in the final executable for stack unwinding (the destruction of local objects as the exception traverses functions) and
try
/ logiccatch
(the end of stack unwinding ).For signals, that control code cannot be placed around any particular line of code because signals are received "outside", like a stone being thrown at you. They can happen at any time.
Even if you think a
SIGSEGV
happens, or is thrown , on the line accessing the wrong memory location, it actually doesn't, or doesn't have to (as far as I know). The signal does not have to be received at the moment that said memory is accessed (that is, it is not launched on the line that detects the situation), but it can come with a certain delay, or never arrive if the accessed memory is also it belongs to your program (to another object, although in this case you will possibly observeUB
- undefined behavior - in execution).