File: exceptions.c

package info (click to toggle)
bock 0.20.2.1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,228 kB
  • ctags: 1,370
  • sloc: ansic: 7,367; java: 5,553; yacc: 963; lex: 392; makefile: 243; sh: 90; perl: 42
file content (101 lines) | stat: -rw-r--r-- 2,168 bytes parent folder | download | duplicates (3)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* A 'C' rendering of the example in section 11.4 of the JLS */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <setjmp.h>

struct exception;
extern struct exception *newdbzexception(void);
extern struct exception *newnullexception(void);
extern struct exception *newtestexception(const char *);
extern void Test_main(int, const char *const *);
extern int Test_thrower(const char *);

#define try { jmp_buf handler, *oldhandler=curhandler; if (setjmp(handler)==0) { curhandler=&handler;
#define catch curhandler=oldhandler; } else { curhandler=oldhandler;
#define endtry } }
#define throw(e) { caught=e; longjmp(*curhandler, 1); }

jmp_buf *curhandler;

struct exception { const char *class; const char *message; };

struct exception *caught;

struct exception *
newdbzexception(void)
{
	struct exception *n=malloc(sizeof(struct exception));
	n->class="java.lang.ArithmeticException";
	n->message="/ by zero";
	return n;
}

struct exception *
newnullexception(void)
{
	struct exception *n=malloc(sizeof(struct exception));
	n->class="java.lang.NullPointerException";
	n->message="(null)";
	return n;
}

struct exception *
newtestexception(const char *s)
{
	struct exception *n=malloc(sizeof(struct exception));
	n->class="TestException";
	n->message=s ? s : "(null)";
	return n;
}

void Test_main(int argslength, const char *const *args)
{
	volatile int i;

	for (i=0; i<argslength; i++) {
		try
			Test_thrower(args[i]);
			printf("Test \"%s"
			   "\" didn't throw an exception\n", args[i]);
		catch
			printf("Test \"%s"
			   "\" threw a %s"
			   "\n    with message: %s\n",
			   args[i], caught->class, caught->message);
		endtry
	}
}

int Test_thrower(const char *s)
{
	try
		if (strcmp(s, "divide")==0) {
			throw(newdbzexception());
		}
		if (strcmp(s, "null")==0) {
			throw(newnullexception());
		}
		if (strcmp(s, "test")==0) {
			throw(newtestexception("Test message"));
		}
	catch
		printf("[thrower(\"%s\") done]\n", s);
		throw(caught);
	endtry

	printf("[thrower(\"%s\") done]\n", s);
	return 0;
}

int
main(int ac, const char *av[])
{
	try
		Test_main(ac-1, &(av[1]));
	catch
		puts("Uncaught exception!");
	endtry
	return 0;
}