Linux system programming: setjmp and longjmp function.

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

#include <stdio.h>

#include <setjmp.h>

//jmp_buf: Array, save the stack information operating environment

jmp_buf buf;

double Divide(double a, double b)

{

if (b == 0.0)

{

longjmp(buf, 1); // throw

}

else

return a / b;

}

//Setjmp saves the current stack information, the successful return of 0, when the execution to longjmp, 

//Restore the stack information is to jump to the setjmp position to execute setjmp

//The longjmp function return value according to the given parameters

int main(void)

{

int ret;

ret = setjmp(buf);

if (ret == 0) // try

{

printf("division ...\n");

printf("%f\n", Divide(5.0, 0.0));

}

else if (ret == 1) // catch

{

printf("divisiong by zero\n");

}

return 0;

}

The operation results:

division ...

divisiong by zero

In fact, the last error processing mode is c++ exception handling model

The above is equivalent to:

#include <iostream>

using namespace std;

double Divide(double a, double b)

{

if (b == 0.0)

{

throw 1; // throw

}

else

return a / b;

}

int main(void)

{

try // try

{

cout<<"division ..."<<endl;

cout<<Divide(3.0, 0.0)<<endl;

cout<<Divide(5.0, 0.0)<<endl;

}

catch (int) // catch

{

cout<<"divisiong by zero"<<endl;

}

return 0;

}

The operation results.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Helena at November 13, 2013 - 12:04 PM