I have a strange question that I have always thought about, but never seen in practical use. I am looking for justification to be enough.
When is a null pointer / reference exception handled preferable for performing a null check? If at all.
This applies to any language that needs to deal with null pointers / references that have exception handling functions.
My usual answer to this would be to do a null check before doing anything with a pointer / reference. If not null, continue as usual and use it. If null, handle the error or raise it.
ie, (in C #)
string str = null; if (str == null) {
However, if we do not check and just blindly use it, an exception will be thrown.
string str = null; int length = str.Length;
As an exception, we could probably catch him, so nothing prevents us from doing this (or is there?):
string str = null; try { int length = str.Length;
Now I admit that this is not the cleanest code, but it is no less working code, and I would not do it normally. But is there a design template or something where this is useful? Perhaps more useful than doing a direct, zero check in advance.
The only cases I can imagine that this can be useful are a multi-threaded environment in which an unprotected shared variable gets too much value. But how often does this happen? Good code that protects variables will not have this problem. Or, perhaps, if someone wrote a debugger and wanted the exception to be thrown open only for wrapping it or something else. Maybe an invisible performance advantage, or eliminates the need for other things in the code?
I may have answered some of my questions, but are there any other possibilities for this? I'm not looking for โdo it just because we canโ examples or just poorly written code, but practical use for it. Although I will be fine, "there is no practical use for this, check."