I think Associative Array should throw Exception

Jesse Phillips Jesse.K.Phillips+D at gmail.com
Tue Sep 1 18:20:17 UTC 2020


This is going to be a hard one for me to argue but I'm going to 
give it a try.

Today if you attempt to access a key from an associative array 
(AA) that does not exist inside the array, a RangeError is 
thrown. This is similar to when an array is accessed outside the 
bounds.

```
string[string] dict;
dict["Hello"] // RangeError

string[] arr;
arr[6] // RangeError
```

There are many things written[1][2] on the difference between 
Exception and Error.

* Errors are for programming bugs and Exceptions are environmental
* Exceptions can be caught, Errors shouldn't be (stack may not 
unwind)
* Exceptions are recoverable, Errors aren't recoverable
* Errors can live in nothrow, Exceptions can't
* Always verify input

I don't have an issue with the normal array RangeError, there is 
a clear means for claiming your access is a programming bug. 
However associative arrays tend to have both the key and value as 
"input."

Trying to create a contract for any given method to validate the 
AA as input becomes cumbersome. I would say it is analogous to 
`find` throwing an error if it didn't find the value requested.

Using RangeError is nice as it allows code to use array index 
inside `nothrow.` But again, can we really review code and say 
this will be the case? We'd  have to enforce all access to 
associative arrays to be done using `in` and checked for null. 
Then what use is the [] syntax?

Is it recoverable? I would say yes. We aren't actually trying to 
access memory outside the application ownership, we haven't put 
the system state into a critical situation (out of memory). And a 
higher portion of the code could easily decide to take a 
different path due to the failure of its call.

"if exceptions are thrown for errors instead, the programmer has 
to deliberately add code if he wishes to ignore the error."

1. 
https://stackoverflow.com/questions/5813614/what-is-difference-between-errors-and-exceptions
2. https://forum.dlang.org/thread/m8tkfm$ret$1@digitalmars.com


More information about the Digitalmars-d-learn mailing list