I think Associative Array should throw Exception
Steven Schveighoffer
schveiguy at gmail.com
Thu Sep 3 15:12:14 UTC 2020
On 9/3/20 10:43 AM, Jesse Phillips wrote:
> On Tuesday, 1 September 2020 at 18:55:20 UTC, Steven Schveighoffer wrote:
>> On 9/1/20 2:20 PM, Jesse Phillips wrote:
>>
>>> Using RangeError is nice as it allows code to use array index inside
>>> `nothrow.`
>>
>> This is the big sticking point -- code that is nothrow would no longer
>> be able to use AAs. It makes the idea, unfortunately, a non-starter.
>>
>> What is wrong with using `in`? I use this mostly:
>>
>> if(auto v = key in aa) { /* use v */ }
>>
>
> I think that actually might be my point. If you need nothrow then this
> is what you need to do.
>
> For breaking nothrow code using the [] syntax, I'd say it is already
> broken because the behavior is to throw and the above is how you would
> check that it won't.
int[int] aa;
aa[4] = 5;
auto b = aa[4];
How is this code broken? It's valid, will never throw, and there's no
reason that we should break it by adding an exception into the mix.
> The issue is, associative arrays throw an "uncatchable" error. Meaning
> code is written to catch the error (because it works). And correctly
> written `nothrow` code needs to use `in` to be properly nothrow.
The big issue is -- is accessing an invalid index a programming error or
an environmental error? The answer is -- it depends. D has declared, if
you use the indexing syntax, then it's a programming error. If you want
it not to be a programming error, you use the key in aa syntax, and
handle it.
The other thing you can do is use a different type, if you don't want to
deal with the verbose syntax, but still want to catch environmental
errors. A wrapper type is possible.
-Steve
More information about the Digitalmars-d-learn
mailing list