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

Meta jared771 at gmail.com
Tue Dec 31 05:58:28 PST 2013


On Tuesday, 31 December 2013 at 12:42:33 UTC, 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.
>
> Or is Array[Key] with a key that is not in the array and bounds 
> checking disabled undefined behavior?

It seems to me like it's more or less an artifact from earlier D, 
maybe even back to D1. It's possible that it was designed like 
that so AAs behave the same way on accessing a non-existent index 
as normal arrays, for simplicity I suppose (though anyone that's 
used an AA in another language would probably find this behaviour 
weird). Item not found is not really a logic error, and not 
really deserving of a RangeError (who wants their program to 
crash when something as simple as an AA lookup fails?), but it's 
not too hard to get around. You have both `value in AA`, which 
returns a pointer that's null if the value is not found, and 
`AA.get(value, default)`, which returns `default` if `value` is 
not found.


More information about the Digitalmars-d mailing list