Runtime errors in functions
Functions callable from SPL, either written in SPL or in a native language, might need to indicate that an error occurred. Because SPL has no exceptions, the two most common approaches to indicating errors are return codes and mutable error parameters.
When a function is called for its side-effect alone, its return value can indicate errors. The Standard Library function fclose() calls the underlying fclose() function that is a part of the standard C library. Closing a file has no inherent return value, so normally nothing is returned. However, its return value can be used to indicate the type of error, if any was encountered.
When a function does return a value, but the valid results are
constrained to a certain range, the result can still be used for an
error code. For example, the Standard Library function parseNumber() takes
a string to parse and a mutable integer to write the result into.
On success, parseNumber() returns the number of
bytes it read from the string. On error, parseNumber() returns -1
.
In this instance, 0
and all positive values are valid
results, so the error code must be negative.
The second technique for indicating failures with functions is
a mutable error parameter. If an error occurs, the function writes
the error type into the mutable parameter that was passed into it.
Use 0
to indicate that no error occurred. Any other
value indicates that an error occurred, and different values can represent
different error codes. (This technique is the same as program return
codes in Unix-based systems.) When functions must return values, and
all values that they can return are legal, using a mutable error parameter
is the only option.
For example, freadLine() from the Standard Library reads a line from a file. The line itself is returned as a string, and all string values are valid. To report errors, the final parameter is a mutable integer.
If possible, use an error-return code from the function. If all
return values from the function are valid, then make the last parameter
of the function a mutable int32
, and write the error
code into that value. If there were no errors, the value is 0
after
the function returns. Use different values to indicate different kinds
of errors, and document the value-to-error mapping with the function.