next up previous contents
Next: Measuring Performance Up: A Guide to Debugging Previous: trace

Trapping Errors

Darwin offers two built-in functions which help users write programs which handle errors in a graceful manner and return meaningful, easy to understand messages. By default, Darwin immediately halts execution of a procedure when it encounters an error. It provides a brief message of what has transpired and waits for the user to resume entering statements. The traperror function allows us to override this behaviour.
traperror(exp : expression)
When an expression is ``wrapped'' inside of a traperror function, errors which occur during the evaluation of exp do not cause Darwin to halt execution. Instead, the error message is returned by the traperror function in the form of a string item. If no error occurs, the evaluation of exp is returned.

> msg := traperror( 100 / 20 );                 # all is okay.
5
> msg := traperror( undefined_symbol / 20 );    # this is an error
msg := invalid term in product
After the second call to traperror above, we can write code to examine the contensts of msg and act accordingly. One option would be to halt the execution of Darwin (as it does by default) but include information about the assigned values to elements of exp. We can stop execution and print out these values via the error function.
error(errormsgs)
This command returns to the top level of execution and issues the error messages errormsgs.
> weird_function := proc( a, b )
>   msg := traperror( a ^ log( b ) );
>   if ( type (msg, string) ) then              # an error occured
>     error(' An error occurred in weird_function. Arguments: ', a,b);
>   fi;
> end:
>
> weird_function(1, d);
Error, (in weird_function) 
 An error occurred in weird_function. Arguments: , 1, d
We can exploit this tandem of functions to help aid in the debugging process. If you encounter a ``fragile'' routine displaying seemingly inconsistent behaviour, inserting traperror and error function calls within the code may greatly reduce the amount of time spent searching for the problem.


next up previous contents
Next: Measuring Performance Up: A Guide to Debugging Previous: trace
Gaston Gonnet
1998-09-15