File: restart.5c

package info (click to toggle)
nickle 2.47-1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 2,112 kB
  • ctags: 3,255
  • sloc: ansic: 30,401; yacc: 1,843; sh: 865; lex: 838; makefile: 202
file content (43 lines) | stat: -rw-r--r-- 880 bytes parent folder | download | duplicates (2)
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
/*
 * Demonstrates using continuations to
 * restart execution after correcting
 * an exceptional condition.
 *
 * Copyright © 2001  Bart Massey.
 * All Rights Reserved.  See the file COPYING in this directory
 * for licensing information.
 *
 * Bart 2001/06/03
 */

exception div0_attempt(continuation c);

rational function f(int x) {
    continuation c;
    int y;
    if ((y = setjmp(&c, 0)) != 0) {
	printf("restarted after exception\n");
	x = y;
    } else {
	if (x == 0) {
	  printf("raising exception\n");
          raise div0_attempt(c);
	}
    }
    printf("returning value\n");
    return 1 / x;
}

rational function protected_f(int x) {
    try {
	return f(x);
    } catch div0_attempt(c) {
	printf("restarting after exception\n");
	longjmp(c, 1);
    }
    printf("internal error\n");
    return 0;
}

printf("%g\n", protected_f(2));
printf("%g\n", protected_f(0));