Why exceptions for error handling is so important
Tobias Müller via Digitalmars-d
digitalmars-d at puremagic.com
Mon Jan 12 22:50:15 PST 2015
"H. S. Teoh via Digitalmars-d" <digitalmars-d at puremagic.com> wrote:
> On Mon, Jan 12, 2015 at 06:06:19PM +0000, Tobias Müller via Digitalmars-d wrote:
>> C#'s Dictionary has TryGetValue that returns a bool in addition to the
>> normal indexing operator [] that throws, exactly for that reason. And
>> this is no exception (no pun intended), there are several cases like
>> that in C#. IMO there's something wrong if you have to resort to such
>> code duplification.
>
> And what exactly should operator[] return if a key wasn't found?
>
> The only sane way is to have the user specify a default value if the key
> wasn't found, since not all types have a null value (and besides, what
> if null is a valid value in the dictionary?). IOW something like
> TryGetValue that takes multiple arguments instead of operator[].
Just stick with one.
Some kind of Optional<T> would be a good fit.
> You really should be using operator[] only when the key is expected to
> exist. If during normal operations there's a 50% chance the key doesn't
> already exist, you shouldn't be using [].
I know that and this is exactly the point. You have two methods that do
almost exactly the same just with different error handling and you have to
choose based on what the caller considers an error.
It's often the case that only the caller can decide what is an error and
what not. The designer of an API has to predict all those cases and provide
different methods for each case.
The problem with exceptions is, that the *callee* has to decide, not the
caller.
More information about the Digitalmars-d
mailing list