This question (How to catch segmentation fault in Linux?) has a lot of info on doing this, including good wording on some of the problems with it, so read all the answers and comments.
Information gleaned from that post:
- Supposedly it is possible with MSVC via
__try
and __catch
- Dereferencing an unmapped pointer ultimately ends with a seg fault signal being sent to the process. You can catch this signal with a custom handler, but it's technically UB to return from it.
- Some third-party libraries exist that can convert the signal to an exception on some Linux platforms. (How they do it may be questionable.)
- It might not even make sense to try to recover from a seg fault.
Does it make sense to try to catch a bad dereference?
Dereferencing a bad pointer is something that you might not be able to catch by checking the pointer. It might be randomly pointing to valid memory, in which case you'll probably end up with some odd UB.
Modern C++ avoids some of the pointer issues by avoiding owning pointers altogether (using RAII pointers instead). You can still pass the pointer (as a non-owned pointer). A good design with smart pointers makes it easier to manage lifetime issues like dangling references and uninitialized/garbage values. But it won't fix all the possible issues.
It can still be useful to check/sanitize pointers in some cases, such as at API boundaries. e.g. In exposed functions that take pointers as input.
If you're having a lot of trouble with pointers, maybe it's a sign that you need to simplify your design or find a better way to manage pointers?