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

John Colvin john.loughran.colvin at gmail.com
Tue Dec 31 05:39:25 PST 2013


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.


More information about the Digitalmars-d mailing list