The Right Approach to Exceptions

H. S. Teoh hsteoh at quickfur.ath.cx
Sun Feb 19 19:36:02 PST 2012


On Sun, Feb 19, 2012 at 09:17:23PM -0600, Andrei Alexandrescu wrote:
> On 2/19/12 9:06 PM, H. S. Teoh wrote:
[...]
> >Do you have a concrete scenario in mind where such a decision would
> >actually be useful? Otherwise we'll just end up with boilerplate code
> >copy-n-pasted everywhere of the form:
> >
> >	auto retries = SomeArbitraryNumber;
> >	do {
> >		try {
> >			...
> >		} catch(Exception e) {
> >			if (e.is_transient&&  retries-->  0)
> >				continue;
> >			throw e;
> >		}
> >	} while(false);
> >
> >But since this block is completely independent of what's inside the
> >try block, why not just put it where the exception is generated in
> >the first place?
> 
> I explained this. The raise locus does not have access to the
> high-level context.
[...]

This is why I'm liking the Lisp model more and more. The lower level
code knows best what recovery strategies are available. But it can't
make that decision at that level. So you need the higher level code to
make this decision. But if you simply unwind the stack all the way back
up to the higher level code, then you've lost the opportunity of reusing
the execution context of the lower level code to perform the recovery.
You have to start from scratch. You also have no other recovery
strategies available, since the original execution context is gone. The
only options left are retry or abort.

By having the high-level code register a delegate which can make this
sorts of decisions, when the low-level code *does* encounter a problem
it will be able to perform the chosen recovery procedure immediately,
rather than throwing away the entire execution context and perhaps
having to reestablish all of it again later.

This doesn't mean the low-level network socket that encounters the
problem will be able to run the recovery right there; you do have to
unwind the stack to some point where intelligent recovery is possible.
But the point is that this is often lower down in the call stack than
the code which is qualified to make decisions about which recovery
strategy should be used. That's why you want to encapsulate the code
that makes this decision in a delegate which is run at the lower-level
code where intelligent recovery takes place.


T

-- 
Life is too short to run proprietary software. -- Bdale Garbee


More information about the Digitalmars-d mailing list