The day of Leisure read LUA source code, found that the original C language except Goto another way to handle the exception. Both Setjump longjump two functions, setjump equivalent to try,longjump equivalent to a catch. Unlike Goto, Longjump is global and has a broader scope than Goto. Here's a simple usage:
#include <stdlib.h>
#include <setjmp.h>
Jmp_buf jumper;
int fdf (int A, int b) {
if (b = = 0)
{ //can ' t divide by 0
longjmp(jumper,-3); Skip to the jmp point where jumper is located , and3 corresponds to the specific exception code.
}
return A/ B;
}
int Main (int argc, char **argv)
{
int jstatus = setjmp(jumper); equivalent to java catch, if a jumper exception occurs, it jumps back to this jmp Point
if (jstatus = = 0) {//First time execution is correct setjmp return 0.
int a = 1;
int B = 0;
printf("%d/%d", A, b);
int result = fdf(A, b);
printf("=%d\n", result);
}
Else if (jstatus = =-3)
printf("--Error:divide by zero\n");
Else
printf("Unhandled Error case");
}
C Language Catch exception