Is there an easy way to throw custom null pointer exception in c++?
My idea was to redefine this pointer, but it has 3 problems:
- Not using
thisthrows standard Acces Violation Exception - Pointer is checked every time it is used
-
Visual studio show this as
InteliSenseerror (compilable) (do not know what other compilers do)#include <iostream> #define this (this != nullptr ? (*this) : throw "NullPointerException") class Obj { public: int x; void Add(const Obj& obj) { this.x += obj.x; // throws "NullPointerException" //x = obj.x; // throws Access Violation Exception } }; void main() { Obj *o = new Obj(); Obj *o2 = nullptr; try { (*o2).Add(*o); } catch (char *exception) { std::cout << exception; } getchar(); }
Since
thiscan never, ever benullptr, compilers are free to treatthis != nullptrthe same astrue. What you’re trying to do fundamentally doesn’t make sense. You can’t use exceptions to catch undefined behavior. The only waythiscan benullptris through undefined behavior.Dereferencing a
nullptris undefined behavior (8.3.2). This is trying to use an exception to catch undefined behavior. Fundamentally, you cannot do that in C++.For one obvious reason this is undefined, consider this: