Last active
May 21, 2019 11:47
-
-
Save mori0091/45b275f61ac802fcabe7fb5dede7ca73 to your computer and use it in GitHub Desktop.
Simple exception handling in C11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <errno.h> | |
#include <setjmp.h> | |
#include <stdarg.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct { | |
const char* msg; | |
jmp_buf e; | |
} Ctx; | |
/* | |
* Ctx ctx; | |
* TRY(Ctx *ctx) { | |
* // statement... | |
* } else { | |
* // exception-handler... | |
* } | |
*/ | |
#define TRY(ctx) if (!setjmp((ctx)->e)) | |
/* | |
* raise(Ctx *ctx, const char *fmt, ...) - throw a formatted string as an | |
* exception | |
*/ | |
void raise(Ctx *ctx, const char *fmt, ...) { | |
/* construct formatted string */ | |
va_list ap; | |
va_start(ap, fmt); | |
int len = vsnprintf(NULL, 0, fmt, ap); | |
if (len < 0) { | |
fprintf(stderr, "vsnprintf(NULL, 0, fmt, ...):%s\n", strerror(errno)); | |
exit(1); | |
} | |
char *buf = malloc(len + 1); | |
if (vsnprintf(buf, len + 1, fmt, ap) < 0) { | |
fprintf(stderr, "vsnprintf(buf, len, fmt, ...):%s\n", strerror(errno)); | |
exit(1); | |
} | |
/* throw as an exception */ | |
ctx->msg = buf; | |
longjmp(ctx->e, -1); | |
} | |
void g(Ctx *ctx, int n) { | |
int i = 0; | |
for (;;) { | |
printf("%d", i); | |
if (i == n) { | |
raise(ctx, "Exception!:%d", i); | |
} | |
i++; | |
} | |
} | |
void f(int n) { | |
Ctx ctx; | |
TRY(&ctx) { /* try */ | |
g(&ctx, n); | |
} else { /* catch */ | |
printf("\nException caught:%s\n", ctx.msg); | |
free((void *)ctx.msg); | |
} | |
} | |
int main(int argc, char **argv) { | |
for (int i = 0; i < 10; ++i) { | |
f(i); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple exception handling in C. (C++ or Java like try-catch clause)
setjmp()
andlongjmp()
jmp_buf
object is encapsulated in aCtx
struct.TRY()
to setup thejmp_buf
object (callsetjmp()
)Ctx
object is passed to a callee function which may raise a exception.raise()
, an exception message is composed into theCtx
object and returned to caller.