On Wednesday, September 14, 2016 16:52:19 Bauss via Digitalmars-d wrote: > Can someone riddle me this, why D gives an access violation > instead of ex. a null reference exception? > > Like let's say you have a field that's a class and you forget to > give it a value. Now that will cause an access violation, but > generally access violations are an indication that you're program > has reached a nasty state and can't be recovered. Hence why you > cannot catch it by doing a normal catch block for "Exception", > but has to do on "Throwable" (Idk if "Error" works for?) Now > that's a problem, because in that particular case the program may > still work without being in an unrecoverable state. > > Of course it can be resolved by catching it, but what about > actual unrecoverable access violations? You will be shadowing > those too then. > > This is especially a problem when you work with 3rd party > libraries where you basically have no control over what happens. > > Is there a way around this, to make thins like not assigning an > instance to a class cause some null reference exception or is > there a specific reason why it exactly throws an access violation > error.
Dereferencing null is generally considered to be a program bug and thus should be treated as unrecoverable - just like failed assertions are considered to be unrecoverable, which is why they throw AssertErrors and not AssertExceptions. So, if we were going to have null-checks built-in, then we'd throw something like NullDereferencingError and not NullException. However, Walter's stance on this is that the CPU already does the null checks for you - that's why you get a segfault on *nix or an access violation on Windows. The CPU checked. Any additional checks would therefore just be unnecessary overhead. If you don't want to have problems with dereferencing null pointers or references, then check for null in the cases where a pointer or reference might be null. - Jonathan M Davis