Previous: , Up: Errors   [Index]


11.2 Trapping Errors

Having errors terminating programs is not suitable at all times, especially when the library functions hold the program terminating error generation as the preferred method of dealing with failures.

Trapping errors, barring program termination and having an indication on whether the attempted operation succeeded appear as useful implements and aime provides for them.

The two interfaces limiting error propagation are:

trap

integer trap(object, &...);

and:

wrap

integer wrap(&, object, &...);

See Error Trapping Functions.

trap’ executes the function indicated by its first argument, passing it its remaining arguments. It evaluates 0 if the function call succeeds, non zero when it fails and the program execution would be otherwise terminated.

void
rem(real &r, real x, real y)
{
    r = fmod(x, y);
}

The ‘rem’ function sets its first argument to the floating-point remainder of dividing its second argument to its third. The function will fail if y is 0 - the aimefmod’ will fail first and since ‘rem’ is not trapping the error, the failure is propagated further.

    real a;

    rem(a, 2.5, .75);

will set a to .25.

    real a;

    rem(a, 2.5, 0);

will have the program terminated, with a division by zero message displayed.

    real a;

    trap(rem, a, 2.5, 0);

will continue to display the message, but the program will continue execution. The value of a will not be modified.

    real a;

    trap(rem, a, 2.5, 1.75);

sets a to .75.

trap’ allows error conditions to be tested and corrective actions to be taken.

    file f;

    if (trap(f_open, f, "directory/!?#$%^&*(),707", OPEN_READ, 0)) {
	do_something_else();
    }

wrap’ works much like ‘trap’, setting its first argument to the result of the call of the function indicated by its second. Its remaining arguments are passed to the called function.

    wrap(a, fmod, 2.5, 1.125);

has a set to .25 and ‘wrap’ returning 0.

    wrap(a, fmod, 2.5, 0);

has a left unchanged and ‘wrap’ returning non zero.

trap’ and ‘wrap’ allow limiting the error propagation on function level. There is no finer error trapping level that aime allows.

The two functions may be used in conjunction with ‘error’ to jump non locally, with ‘error’ defaulting control and one of the error trappers assuming it.


Previous: Generating Errors, Up: Errors   [Index]