Null references and access violation

Marco Leise via Digitalmars-d digitalmars-d at puremagic.com
Wed Sep 14 10:37:57 PDT 2016


Am Wed, 14 Sep 2016 16:52:19 +0000
schrieb Bauss <jj_1337 at live.dk>:

> Can someone riddle me this, why D gives an access violation 
> instead of ex. a null reference exception?

Access violations cost exactly 0. Noone needs to do anything
extra for this check that isn't done by the CPU already. The
next step is an assertion (which I think is done in debug mode
when you call a method on a null object). That's still not
recoverable, just like out of memory situations in D.
Compare for example in-contracts, where you assert for
not-null. Those throw unrecoverable errors as well unless you
turn them from

  assert(obj !is null);

into 

  if (obj is null) throw new NullPointerException();

(And that's what the compiler in its current state would
probably insert for you on every access to the object.)

D is somewhat consistent in making null pointers and other
contracts/assertions fatal errors that end program execution.
In other words: Everything that's a fault in the program logic
gives you a rather harsh exit, while unforseeable situations
like network errors or incorrect user input are handled by
exceptions. Walter mentioned that when a program is run inside
a debugger, access violations are the easiest problem for the
debugger, while D exceptions on Linux are not as easy to
break on.

I understand the sentiment though. I've seen a Karaoke
software throw exceptions because no item was selected in a
list box. If that was an access violation you could not
have acknowledged the OutOfBounds/NullPointer message, selected
an item and continued. Depending on how and where the software
is used, one or the other is a better default.

We have had some interesting proposals on not-null references
(as NullPointerExceptions are seen as a mistake in retrospect
by language designers [citation needed]) and "remembering"
what line of code has safe access to the object. E.g.
everything in "if (obj) { ... }" can safely access the object.

-- 
Marco



More information about the Digitalmars-d mailing list