Why do associative arrays throw an Error (RangeError) on value not found?

Jonathan M Davis jmdavisProg at gmx.com
Tue Dec 31 14:51:27 PST 2013


On Tuesday, December 31, 2013 13:39:25 John Colvin wrote:
> On Tuesday, 31 December 2013 at 12:55:59 UTC, Jacob Carlborg
> 
> wrote:
> > On 2013-12-31 13:42, Supernova wrote:
> >> Why do associative arrays throw an Error (RangeError) on value
> >> not found?
> >> 
> >> This seems like it would be inefficient to check for, so a
> >> recoverable
> >> Exception (ItemNotFoundException?) would seem to be more
> >> appropriate.
> > 
> > How would ItemNotFoundException be any more efficient? The idea
> > is that the error should not be recoverable. If you get an
> > RangeError in your code you have made a logical error.
> > 
> > You need to explicitly check if a key is available in the
> > associative array before accessing it, something like this:
> > 
> > if (auto value = key in aa)
> > 
> >     writefln("key %s was found with the value %s", key, value);
> > 
> > else
> > 
> >     writefln("key %s was not found", key);
> 
> Doesn't that duplicate the work of discovering whether the key is
> there or not? I guess it would depend on the implementation.

Not really. If you don't know whether it's there or not, use the in operator. 
If you know that it's there, then use the subscript operator.

auto value = key in aa; //Maybe it's there, maybe not
auto value2 = aa[key2]; //It's definitely there and is a bug if it's not

You'd get a double lookup if the in operator returned a bool and then had to 
use the subscript operator to fetch it, but fortunately, in returns a pointer 
to the value (or null if it's not there), which is more efficient and a lot more 
useful.

- Jonathan M Davis


More information about the Digitalmars-d mailing list