PDA

View Full Version : [SOLVED] Exception Handling in gcc



vgokul
October 7th, 2009, 03:36 PM
Hello all,
I am new to exception handling and I have some problems. Can you please help?

I have a legacy code that has divide by zero error at the start for the first few function calls but has no functional effect if they are ignored (I have checked this in Windows with SEH). Now I need the same in the Linux environment and I tried in a smaller test code that is representative of my original code - please see the code below. The exception is ignored the first time but in the second call float point exception occurs. Can you please let me know how to handle this? Is this the correct way to handle this?


#include<stdio.h>
#include<signal.h>
#include<setjmp.h>
void test();
jmp_buf sjbuf;/*Buffer to store stack position*/

void handler(int signum)
{
if(signum == SIGFPE)
printf("Handler called - Signal error is SIGFPE\n");
signal(SIGFPE, handler);/*Refresh the handle*/
longjmp(sjbuf,1); /* return to saved state */
return;
}

int main()
{
signal(SIGFPE, handler);
//signal(SIGFPE, SIG_IGN);

printf("Inside main\n");
if(setjmp(sjbuf)==0) /* save current stack position */
{
printf("Saved Stack\n");
test();
}

printf("Continuing main\n");
if(setjmp(sjbuf)==0) /* save current stack position */
{
printf("Saved Stack\n");
test();
}
getchar();
return 1;
}
void test()
{
int x;
int y;
printf("Inside test\n");
y= 0;
x = 1/y;

}

Regards
V.Gokul

dwhitney67
October 7th, 2009, 03:43 PM
Use sigsetjmp() so that your signal handler setup is preserved.



...
if (sigsetjmp(sjbuf, SIGFPE)==0)
...

vgokul
October 12th, 2009, 02:23 PM
Hi ,
Thanks. It works.

Is the use of signal and jmp functions the only way to handle this or is there a better way - when the function itself that generates the divide by zero error cannot be changed?

Regards
V.Gokul

PS: Sorry for a delayed response. I was out of office for the last few days.

grayrainbow
October 12th, 2009, 07:55 PM
Divide by zero is in general something undefined. On x86 integer divizon by zero produce hardware exception and Linux will inform you with signal for this, so in this case signals are the best IMO. But...in general Linux does not run only on x86, some platforms will happily consider this as zero.