Data Structures and Algorithms
Errors in C ADTs (cont)

An approach that models reasonably closely the exception handlers of Ada, Java or C++ adds one extra function to each class. As in these languages, the exception can be "caught" at any appropriate level in the program (where enough is known about the operating environment to determine how the error should be handled) by invoking the error function there.

Add an Error function to each class
With this approach, we add to each class a function which can be called at the appropriate level to determine whether an error occurred.
/* vector.h */
typedef struct vector_t *vector;
typedef enum( NoError, SizeMisMatch, NoMemory ) vector_error;

vector ConsVector( int dimension );
vector_error DeleteVector( vector a );
vector_error VectorError();

double DotProduct( vector a, vector b );
The implementation is simple:
#include "vector.h"
static vector_error ve = NoError;

vector_error VectorError() {
    vector_error err;
    err = ve;
    ve = NoError;
    return err;
    }

char *VectorErrorString( vector_error ve ) {
    switch( ve ) {
    	case NoError: return "No Error";
    	case SizeMisMatch: return "Vector size mismatch";
      case NoMemory: return "Insuff memory for Vector";
    	default: return "Unknown Vector Error";
    	}
    }

double DotProduct( vector a, vector b ) {
    if ( LengthVector(a) == LengthVector(b) ) {
        ....
        }
    else {
        ve = SizeMisMatch;
        return 0.0;
        }
    }
Note the additional (optional) VectorErrorString method which produces a printable string explaining the error. This is similar to the perror() method which prints out the latest I/O error as a string. (But note that perror() violates the re-usability rule being suggested here as it outputs the string to standard output and thus is useless in environments, eg most GUI environments, where the notion of stdout may not be useful.)

Now the VectorError() method can be called at any point in the program after the vector class methods have been invoked and the environment is known well enough to determine what action should be taken in response to the error.

double dp;
...
dp = DotProduct( a, b );
if( (ve = VectorError()) != NoError ) {
    printf("Dot product error: %s\n", VectorErrorString( ve ) );
    }
Continue on to Programming Language Notes
Back to the Table of Contents
© , 1998