2020-08-20

return status and error handling

  • it is possible to use a status variable with an object that has status id and group id that is checked for a failure status and use goto to an exit label at the end of the routine where all cleanup is done. gotos in c are local to the current routine. it is a bit like local exceptions
  • the status id is the error or general status code, the group id is a string name of the library the code belongs to. when multiple libraries are used it would otherwise be almost impossible to synchronise error codes so that they are not ambiguous. string names are used because integer ids would again be hard to keep unambiguous
  • doing all clean-up at the end of the routine can save code deduplication. it can be useful to set variables to null values before they have been used so that the clean-up part can know, for example, not to free an unallocated pointer

example

  • this example uses a reference implementation from sph-sc-lib
  • status_declare declares a local variable status_t status = {0, ""};, the other status_* bindings use that variable
  • status_require checks that status.id is status_id_success, which is zero, and goes to exit if not
#include "sph/status.c"

status_t test() {
  status_declare;
  if (1 < 2) {
    status_set_goto("mylib", 456);
  }
exit:
  return status;
}

int main() {
  status_init;
  // code ...
  status_require(test());
  // more code ...
exit:
  return status.id;
}