How do exceptions work from an Operating System’s perspective?
Coming from C++, I can understand exceptions from a programmer’s perspective.
When an exception gets thrown, the stack begins to unwind, and each activation record has the opportunity to catch and handle the exception.
But whose responsibility was it to throw the exception in the first place?
- Is it the Operating System that sends a trigger to the process
telling it to enter it’s “exception handling state?” - Is the
process invoking and handling exceptions in it’s own program space,
unpronounced to the OS?
Here are two crashing programs that illustrate my uncertainty.
int main(){
int i = 1/0; //did the OS tell the process to end?
return 0;
}
#include <exception>
int main(){
throw 11; //did the process tell the OS it needs to end?
return 0;
}
C++ exceptions are part of the language, defined by the language standard, and implemented by the compiler and runtime library. There are other
exceptionsthat are detected by the CPU, like divide by zero or dereferencing a NULL pointer, both are examples of Undefined Behavior in the language standard. Those arefaultsin processor terminology and on x86 for example trigger afault handlerwhich is then serviced by the OS. The OS can then choose to report that fault to the process that caused it, on Unix this is done withsignals. If your process has installed asignal handlerforSIGSEGVfor example, it can handle the fault generated by the CPU when the process dereferences a NULL pointer… that mechanism is separate from the C++ exceptions defined by the language.In your example, when a C++ program
throwsan exception this is entirely handled by the compiler generated code and the language runtime library, there is no kernel call necessary and there is no hardware fault generated by the processor.