For those familiar with languages like Java, and C#, something like NullPointerException shouldn’t come as a surprise. But what about C++? C++ also has exceptions, right?
In C++ reading or writing at address zero is an access violation. By default an access violation will result in the immediate termination of the program. What else results in immediate termination of the program? Division by zero! There is no ArithmeticException, only a swift termination!
The OS’ SDK usually provides a way to catch such access violations and recover from them. This way of catching access violations involves a C callback method and a bit of setup.
Wouldn’t be nice if the setup would be one line of code and the C callback function would throw C++ exceptions behind the scenes?
But it does work like this. At least on Windows and Linux (I don’t have access to a macOS machine), and only with a few select compilers.
Before going further into details I would like to present my test case: define functions which do:
- Division by zero
- Reading from nullptr
- Writing at nullptr
- Write to an empy vector with the subscript operator 
- Read from an uninitialized shared_ptr
Execute them ten times to make sure that this is not only one time “wonder”. Every
try block will
have an instance of a RAII
Message object to make sure that stack unwinding is taking place, and
that we won’t have any resource leaks.