On Monday 17 October 2005 20:07, Jamey Sharp wrote:
> Although if anyone has suggestions about how to make error handling
> an easy part of this API, so that it's natural to check for errors in
> *all* programs, I'd love to hear them. Carl, maybe some of the
> lessons you've learned from designing Cairo could help?
I'm not Carl (obviously) and I don't pretend to speak for him...
In Cairo there's a cairo_t object which gets passed as the first
parameter to every cairo_*() function (I guess xlib's equal would be
the Display pointer). Inside the cairo_t is a status flag. Each
cairo_*() function modifies the status flag inside the cairo_t
structure as necessary. As part of each cairo_*() function's
preconditions it checks the current state. If the state is anything but
good the function returns and doesn't do anything (a noop()).
Therefore the user doesn't have to check the status after each and every
cairo_*() function call, they're free to write "cleaner" code and only
check the status at various way-points.
So instead of code that looks like this:
if (cairo_moveto (cr, x, y) != CAIRO_STATUS_SUCCESS) {
error ();
}
if (cairo_lineto (cr, x, y) != CAIRO_STATUS_SUCCESS) {
error ();
}
if (cairo_set_source_rgb (cr, r, g, b) != CAIRO_STATUS_SUCCESS) {
error ();
}
if (cairo_fill (cr) != CAIRO_STATUS_SUCCESS) {
error ();
}
A user can write code that looks like:
cairo_moveto (cr, x, y);
cairo_lineto (cr, x1, y1);
cairo_set_source_rgb (cr, r, g, b);
cairo_fill (cr);
if (cairo_status (cr) != CAIRO_STATUS_SUCCESS) {
error ();
}
Which is considered easier to read.
As another example, the png library has its users call the setjmp(3)
function to define a location to jump to should an error be
encountered. In this way an application can setup various cleanup
routines at the jumped-back-to location. libpng will jump to this
location when it encounters an error unless you pass in three function
pointers to an init routine: two are function pointers to handle
warnings and errors, and the third is a pointer to user-data which gets
passed to the functions should they be called.