C Language Catch exception

Source: Internet
Author: User
Tags fdf

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

Related Article

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.