Why exceptions for error handling is so important

via Digitalmars-d digitalmars-d at puremagic.com
Mon Jan 12 11:10:00 PST 2015


On Monday, 12 January 2015 at 18:45:22 UTC, H. S. Teoh via 
Digitalmars-d wrote:
> 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[].

Yes, and then think about the original foundation for exceptions.

An exception is mean to resolve situations where you call from a 
higher level layer into a lower level layer (or framework). The 
basic idea is that the higher level layer has information that 
the lower layer does not.

So if you have exceptions with retry you get this:

1. High Level calls into low level

2. Low Level goes "Lord High Level, I am your humble servant, but 
cannot compute 3/0. What shall I do?"

3. High Level ponders for a while and says "replace it with 
infinity and continue"

4. Low Level comes back and say "Lord High Level, I cannot find 
'flowers.png'".

5. High Level responds "Use 'default.png' instead".

6. Low Level comes back crying "I can't find that either".

7. High Level gives up and says "roll back, backtrack..."

Exceptions are basically about deferring decision making from an 
encapsulated context to the calling context.

Without retries, you just have a backtracking mechanism. Don't 
get hung upon the terminology. Use it for writing maintainable 
code!


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

This is getting very normative. Where did you get that 50% from?

If you had exceptions with retry you could just look it up in a 
default directory for instance, or even made a "call" to another 
process to get a substitute value.

Besides, if you are doing validation then it is desirable to get 
an exception for an illegal key.

Don't let a crappy implementation of exception handling define 
general semantics. Improve the implementation instead.


More information about the Digitalmars-d mailing list