| ||
| Home | Modules | Examples |
Error handling in C APIs is fairly cumbersome if you need to check for errors frequently, as you either need to check return values (or parameters) or a global error after each function call to ensure that the next one does not go bad. However, most of the time you would like to call API routines if there has been no error, otherwise skip until the end. libccmio has appropriated error handling ideas from dataflow programming in an attempt to make error handling less cumbersome for the API user. All functions return an error, in case it is convenient, but most functions also take an error pointer, the value of which will be set to the error returned. Should the value of this pointer be an error upon entrance to the function, the function will do nothing. Occasionally you will want to test whether an function call will succeed. In this case, NULL, which is always interpreted as kCCMIONoErr, should be passed to the function and the return value checked for success, otherwise an anticipated failure would cause succeeding functions to do nothing.
Dataflow error handling allows the API user to write code that opens a file, does some reading or writing, and then closes it, without checking for errors until the end. The API guarantees that any return parameters of the function will be usable (i.e not cause a crash when used), unless otherwise documented, and that, should an error occur early on, all memory allocated internally will be properly deallocated. For instance:
err = CCMIOOpenFile(NULL, argv[1], kCCMIORead, &root);
CCMIOGetState(&err, root, kDefaultState, &problem, &state);
... read stuff
CCMIOCloseFile(&err, root);
if (err != kCCMIONoErr)
alert user of error
There are several things to keep in mind when using errors:
CCMIOError err = kCCMIONoErr;unless it is being assigned as a result of an API call (e.g.
CCMIOOpenFile). kCCMIONoErr should always have a value of 0 (zero), it is preferable to compare errors to kCCMIONoErr to avoid confusion, since while !err is a correct test for an error, !CCMIOOpenFile reads like it checks for the failure of the function, but in reality returns true only if there was not an error. Thusif (CCMIOOpenFile(...) != kCCMIONoErr)should be the canonical test.
kCCMIONoNodeErr error: i = 0;
while (CCMIONextEntity(NULL, parentID, kCCMIOField, &i, &child) == kCCMIONoErr)
... do stuff ...
1.2.18