0 day streak
c / expert
Snippet

Non-local Jumps for Error Handling

setjmp and longjmp allow for non-local jumps that bypass the standard function call/return mechanism. This is often used to implement exception-like error recovery where a deeply nested function can return directly to an error handler higher up the call stack.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <setjmp.h>
jmp_buf recovery_env;
void risky_operation(int val) {
if (val < 0) longjmp(recovery_env, 1);
printf("Operation successful: %d\n", val);
}
int main() {
if (setjmp(recovery_env) == 0) {
risky_operation(-5);
} else {
printf("Error caught: Value cannot be negative.\n");
}
return 0;
}
Breakdown
1
jmp_buf recovery_env;
Declares a buffer to store the execution environment (stack pointer, instruction pointer, etc.).
2
if (setjmp(recovery_env) == 0)
Saves the current environment; returns 0 on initial call, and non-zero when returning via longjmp.
3
longjmp(recovery_env, 1);
Restores the environment saved in the buffer, effectively jumping back to the setjmp call point.