Why exceptions for error handling is so important

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Mon Jan 12 10:43:05 PST 2015


On Mon, Jan 12, 2015 at 06:06:19PM +0000, Tobias Müller via Digitalmars-d wrote:
> "H. S. Teoh via Digitalmars-d" <digitalmars-d at puremagic.com> wrote:
> > On Mon, Jan 12, 2015 at 05:22:26PM +0000, Adam D. Ruppe via Digitalmars-d wrote: 
> >> I still wouldn't use them for ordinary flow as a general rule
> >> though, but I think they work well for cases where you ask a
> >> function to do something and it just can't.
> > 
> > Yeah, exceptions are supposed to be ... well, *exceptions*, rather
> > than the norm. :-) If you're using exceptions to do flow control,
> > you're doing something wrong.
> 
> But what's exceptional for you is normal for me.
> 
> 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[].

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 [].


T

-- 
Маленькие детки - маленькие бедки.


More information about the Digitalmars-d mailing list