Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Exception handing problem?? (http://www.go4expert.com/forums/exception-handing-problem-t660/)

pacificcoral 24Mar2006 21:59

Exception handing problem??
 
Hi, I am a C programmer new to C++ and have some questions regarding exception handling. I am using:
g++ 4.01
Suse Linux 9
i486

Try-Catch blocks seem to work when I issue a throw. However, they do not catch illegal statements such as divide by zero, or segmentation faults. For example,

Code: CPP

try{
    throw 1;
}
catch (...) {
    cout<<"Exception caught!"<<endl;
}

OUTPUT: Exception caught.

HOWEVER

Code: CPP

try{
     int a=1, b=0;
     a=a/b;
}
catch (...) {
     cout<<"Exception caught!"<<endl;
}

Ends with a program termination "floating point error"

Am I missunderstanding C++ exception handling, or should the second example be caught? I've tried different complier options (-O0 and -O1), and (-fexceptions) with the same results.

Thanks,
Dan

coderzone 25Mar2006 07:10

Re: Exception handing problem??
 
Thats because divide by zero does not throw and exception and you need to test that and throw the exception yourself. Something like
Code: CPP

if (b == 0)
    throw 1;
else
    a=a/b;


pacificcoral 25Mar2006 08:08

Re: Exception handing problem??
 
Thanks for the info.

So, if I understand you correctly, try-catch can not be used to catch unhandled (un-anticipated) exceptions such as segmentation faults. I was hoping try-catch works similar in C++ as it does in C#, so it can be used to more gracefully handle bugs that would otherwise cause the program to crash.

Can you please describe what type of exceptions ARE caught from the standard library?

Dan

coderzone 25Mar2006 11:26

Re: Exception handing problem??
 
In C++ No exceptions will be caught automatically and you need to be catching them all manually. The C++ in Windows programming catches the segmentation faults and other exception but not the plain Dos based C++.

pacificcoral 25Mar2006 21:20

Re: Exception handing problem??
 
A segmentation fault is difficult to anticipate and protect against. I imagine that g++ in Linux probably generates a signal for this and other type of system errors. How do I go about 'catching' these signals to prevent ugly terminination?

coderzone 25Mar2006 22:16

Re: Exception handing problem??
 
Quote:

Originally Posted by pacificcoral
A segmentation fault is difficult to anticipate and protect against. I imagine that g++ in Linux probably generates a signal for this and other type of system errors. How do I go about 'catching' these signals to prevent ugly terminination?

Actually its not that difficult if the design is done correctly but yes its a difficult job if implemented from middle.


All times are GMT +5.5. The time now is 22:19.