The C language does not have the ability to try catch like Java to handle exception errors. However, you can use the setjmp and longjmp functions to implement the basic logic of error handling.
Setjmp (buffer) saves the current Register status of the program to the buffer array, which is defined by jmp_buf:
# Include <setjmp. h> jmp_buf buffer;
Longjmp (buffer, n) redirects the program stream to the setjmp position and restores the Saved state in the buffer. The second parameter n is an integer. When you jump to the setjmp position through longjmp (buffer, n), the setjmp function returns N. Otherwise, if setjmp is directly executed, zero is returned. According to this feature, we can regard integer N as the error code, so that the execution of setjmp (buffer) will know which error is triggered.
A small example is as follows:
# Include <stdio. h> # include <setjmp. h> jmp_buf buffer; void handle_error () {int err_code = setjmp (buffer); If (err_code! = 0) {printf ("error code: % d \ n", err_code) ;}} void trigger_error (INT err_code) {longjmp (buffer, err_code);} int main () {handle_error (); trigger_error (1); trigger_error (2); Return 0 ;}
In the above Code, trigger_error triggers two errors, both of which are captured by handle_error. This is a simple and complete example of error handling. Since the buffer array for saving the running status should be used in different functions, the buffer should be declared as a global variable, which is not very elegant.
From: http://programmingnote.com/blog? P = 179