Handling exceptions in C with sigsetjmp

The following piece of code proposes an answer to the question "How do I plot a function graph while handling undefined points?". For example, imagine that you provide a method to plot an arbitrary function, and that the user gives a function that is not properly defined (for example when computing x->1/x with x = 0). In practice, that code shows how to use sigsetjmp to handle exceptions in C.

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <unistd.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
sigjmp_buf jmpbuf;
struct sigaction siga;
void handler(int sig)
{
longjmp(jmpbuf, 1);
}
int f(int x)
{
return (1/((x&gt;0)?0:x));
}
void trace(typeof(f) func, int x)
{
float y = func(x);
printf("%f\n", y);
}
int main(void)
{
int x;
siga.sa_handler = handler;
sigaction(SIGFPE, &amp;siga, NULL);
for (x = -5; x &lt; 5; x++)
{
if (sigsetjmp(jmpbuf, 1) == 0) {
trace(f, x);
}
else {
printf("SIGFPE !\n");
}
}
return 0;
}

, ,

Comments are closed.