On the Lack of Exceptions

Lately, I’ve been helping develop a reasonably sized application, which detects errors at every operation. Checking the return value of every function call seems awkward when compared to code that is written in rather informal working environments. Writing code that checks each return value is frustrating when a feature that exists in another language is not available in the current implementation language. A function signature that may allow for the detection of a function’s failure is as follows:

STATUS operation( ArgType1 arg1, ArgTypeN argN );

The only qualm I have with the above function signature is that operation() is inconsistent with the mathematical notion of a function. Instead of having y = f(x), where the parameters to f() are unchanged, the function signature above has a return value set of {SUCCESS,!SUCCESS}, and the result of the operation may be stored at a memory location that is passed as an “out” parameter. Although operation() is less function-like, I like this method more than the use of global variables and additional function calls for error checking.

An apparent problem, or nuisance, occurs when multiple calls to operation() are made and error checking with handling needs to be performed. The code becomes saturated with conditionals and possible duplication of error handling code:


if( SUCCESS != operation(arg1,arg2) )
{
	/* error_handling_code_1 */
}

/* omitted_code_1 */

if( SUCCESS != operation(arg3,arg4) )
{
	/* error_handling_code_1 */
}

/* ommitted_code_2 */

if( SUCCESS != operation(arg4,arg5) )
{
	/* error_handling_code_1 */
}

This situation is just screaming for the use of exceptions. Exceptions would allow the code to be easier to read, and the implementation of the error handling code can be more disjoint from the function call that is experiencing the error.


try
{
	operation(arg1,arg2);
	/* ommitted_code_1 */
	operation(arg3,arg4);
	/* ommitted_code_2 */
	operation(arg4,arg5);
}
catch( ExceptionType1 arg )
{
	/* error_handling_code_1 */
}
catch( ... )
{
	/* if a given exception is not handled here, */
	/* it may be possible to rethrow the exception */
}

Although the target system might not have exception support, having to implement the discussed code helped me appreciate exceptions.

Leave a Reply