NAME
waserror, poperror, nexterror, error, fmterror, silenterror – exception handling for threaded programs

SYNOPSIS
#include <u.h>
#include <libc.h>
#include <thread.h>
#include <error.h>
int     waserror(void);
void    poperror(void)
void    nexterror(void);
void    error(char *err);
void    fmterror(char *fmt, ...);
void    silenterror(char *fmt, ...);

DESCRIPTION
The functions in this library provide an aexception handling mechanism modelled on that in the Plan 9 kernel. A construct such as
try{

if(⋯) raise(exception);

}except{
handle exception
}
using this library becomes:
if(waserror()){
handle exception
}

if(⋯) error("exception");

poperror();
Waserror and poperror are the bracketing elements around the code in which an exception might be raied with a call to error.

Waserror sets a point to which control returns if an exception occurs and returns zero. If the exception occurs, control transfers back to waserror and it then clears the point previously set and returns non–zero.

Poperror clears the exception–return point previously set by waserror.

Error, fmterror and silenterror all raise an error and they all set the error string. Fmterror and silenterror take a format string, while error just takes a simple string. Error and fmterror print the string on standard error as well. Silenterror does not.

Exception contexts bracketed by waserror and poperror can be nested. When an exception has been handled in the innermost context, a call to nexterror transfers it to the next larger context.

EXAMPLES
Using exceptions to free dynamic memory:
if(waserror()){
free(p);
nexterror();
}
p = malloc(something);

if(⋯)
fmterror("%s: %r", x);

free(p);
poperror();
Excerpt from the worker library. The worker calls a user–spcified function that may raise an error. The error is caught and the worker prepares for the next customer:
static void
worker(void *arg)
{
Worker *w;
w = arg;
for(;;){
w–>r = recvp(w–>chan);
if(!waserror()){
w–>r–>func(w, w–>r–>arg);
poperror();
}
reqfree(w–>r);
sendp(workerthreads, w);
}
}

DIAGNOSTICS
Waserror returns non–zero when an error was raised.

SEE ALSO
worker(2)

BUGS
The error stack is only 32 levels deep.

AUTHOR
Sape Mullender
Copyright © 2025 Plan 9 Foundation