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: try{ throw 1; } catch (...) { cout<<"Exception caught!"<<endl; } OUTPUT: Exception caught. HOWEVER Code: 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
Thats because divide by zero does not throw and exception and you need to test that and throw the exception yourself. Something like Code: if (b == 0) throw 1; else a=a/b;
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
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++.
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.