Skip to content

Instantly share code, notes, and snippets.

@mori0091
Last active May 21, 2019 11:47
Show Gist options
  • Save mori0091/45b275f61ac802fcabe7fb5dede7ca73 to your computer and use it in GitHub Desktop.
Save mori0091/45b275f61ac802fcabe7fb5dede7ca73 to your computer and use it in GitHub Desktop.
Simple exception handling in C11
#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;
}
@mori0091
Copy link
Author

Simple exception handling in C. (C++ or Java like try-catch clause)

  • Using setjmp() and longjmp()
  • A jmp_buf object is encapsulated in a Ctx struct.
  • A caller invoke TRY() to setup the jmp_buf object (call setjmp())
  • The pointer to a Ctx object is passed to a callee function which may raise a exception.
  • By calling raise(), an exception message is composed into the Ctx object and returned to caller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment