The Right Approach to Exceptions

H. S. Teoh hsteoh at quickfur.ath.cx
Sat Feb 18 11:52:05 PST 2012


On Sat, Feb 18, 2012 at 08:12:43PM +0100, Martin Nowak wrote:
[...]
> Exception are useful for handling unknown errors and probably to
> bundle error handling at a bigger scope.

But the way exceptions are used in D, they are more like errors than
exceptions. The approach in principle is on the right track, because you
want to be able to write:

	Result_t complicatedFunc(T args) {
		doComplexProcessing(args[0]);
		doMoreComplexProcessing(args[1]);
		doYetMoreComplexProcessing(args[2]);
		...
		return result;
	}

instead of:

	Result_t complicatedFunc(T args) {
		if (doComplexProcessing(args[0]) != OK) {
			return Result_t.FAILURE_A;
		}
		if (doMoreComplexProcessing(args[1]) != OK) {
			return Result_t.FAILURE_B;
		}
		if (doYetMoreComplexProcessing(args[2]) != OK) {
			return Result_t.FAILURE_C;
		}
		...
		return result;
	}

The assumption is that *usually* the computation should succeed, but
exceptional conditions do occur, and sometimes you need to distinguish
between them. For example:

	void doComputation() {
		try {
			result = complicatedFunc(...);
		} catch(FailureA e) {
			/* recover from FailureA */
		} /* FailureB and FailureC considered fatal */
	}


> You don't want to use specific exceptions because it couples unrelated
> code.  The distinction of recoverable Exceptions and non-recoverable
> Errors is good enough in most cases.

Not true, especially in library code. If you try to open a file,
FileNotFoundException should be recoverable, but DiskFailureException
should not. You need to distinguish between them.


> Typed exception being used for local error recovery is about the same
> as using error codes but at a bigger expense. On the plus side
> exception can carry more specific error messages, which could be
> solved for error codes too.

The assumption is that exceptional conditions are, well, exceptional, so
it shouldn't matter if you require extra CPU/memory to handle them.

The worst thing is if we enforce generic exceptions instead of specific
exceptions, and then code that *needs* to distinguish between different
types of errors must pattern-match the error message to tell which one
it is. That is unmaintainable, full of opportunities for bugs and i18n
problems, and is absolutely NOT the way we want to go.


T

-- 
The day Microsoft makes something that doesn't suck is probably the day
they start making vacuum cleaners... -- Slashdotter


More information about the Digitalmars-d mailing list