source: tests/exceptions/message.cfa @ 190a833

Last change on this file since 190a833 was 190a833, checked in by Andrew Beach <ajbeach@…>, 4 weeks ago

Returning to exceptions after a long time and added the ability to provide fields to the virtual table. Added a connected test.

  • Property mode set to 100644
File size: 1.6 KB
Line 
1// Use of the exception system where we provide our own functions.
2
3#include <stdio.h>
4#include <string.h>
5// Using collections/string.hfa leads to a resolution error on snprintf.
6
7exception BadIndexException {
8        int value;
9        int size;
10        char * message;
11};
12
13const char * virtual_msg(BadIndexException * this) {
14        return this->virtual_table->msg(this);
15}
16
17// Array length calculated to ususually be big enough.
18const size_t msg_size = 52;
19
20char * format_bad_index(int value, int size) {
21        char * out = (char *)(void *)malloc(msg_size + 1);
22        snprintf(out, msg_size,
23                "Out of Range Index %d (expected less than %d)", value, size);
24        return out;
25}
26
27const char * msg(BadIndexException * this) {
28        if (this->message) {
29                free(this->message);
30        }
31        this->message = format_bad_index(this->value, this->size);
32        return this->message;
33}
34
35void copy(BadIndexException * dst, BadIndexException * src) {
36        // This is an easy detail to miss, you have to copy the table over.
37        dst->virtual_table = src->virtual_table;
38
39        dst->value = src->value;
40        dst->size = src->size;
41        dst->message = (src->message) ? strndup(src->message, msg_size) : 0p;
42}
43
44void ^?{}(BadIndexException & this) {
45        free(this.message);
46}
47
48vtable(BadIndexException) arrayIndex = {
49        .msg = msg,
50        .copy = copy,
51        .^?{} = ^?{},
52};
53
54// This is not supposed to be a real range check, but that's the idea:
55void failRangeCheck(int index, int size) {
56        throw (BadIndexException){ &arrayIndex, index, size };
57}
58
59int atDefault(int fallback) {
60        try {
61                failRangeCheck(10, 8);
62        } catch (BadIndexException * error) {
63                printf("%s\n", virtual_msg(error));
64        }
65        return fallback;
66}
67
68int main() {
69        int value = atDefault(5);
70        printf("%d\n", value);
71}
Note: See TracBrowser for help on using the repository browser.