c / expert
Snippet
Exception Handling Emulation via Non-Local Jumps with setjmp and longjmp
Non-local jumps via setjmp and longjmp allow control flow to bypass standard function return stack frames. Calling setjmp saves the execution context, while longjmp restores that saved context, effectively creating an exception handling mechanism in pure C.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>#include <setjmp.h>static jmp_buf exception_buffer;void process_data(int value) {if (value < 0) {longjmp(exception_buffer, 101);}}int main(void) {int error_code = setjmp(exception_buffer);if (error_code == 0) {process_data(-5);} else {printf("Caught exception code: %d\n", error_code);}return 0;}
Breakdown
1
static jmp_buf exception_buffer;
Declares execution context buffer storing CPU register states.
2
longjmp(exception_buffer, 101);
Restores CPU registers saved in jmp_buf, unwinding execution back to setjmp site with code 101.
3
int error_code = setjmp(exception_buffer);
Saves current execution context; returns 0 initially, and non-zero upon longjmp restoration.