C language error handling -- setjmp & longjmp

Source: Internet
Author: User
Tags try catch

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.