Tutorial :Can't catch atan2 domain error



Question:

I am using a thirdparty library eg. Lib::ValueType value. I then do a call to a member function, value.theta() which performs some mathematical operations including a call to atan2 from <cmath>. Sometimes the theta component is empty and an "atan2: domain error" is thrown. However, I can't catch the exception even by wrapping try{}catch(...) around the suspect code.

I am using C++ Builder 2009, any idea as to how the exception is being thrown and not being caught by the IDE, or my code. The error pops straight up to the screen as a dialog. I have selected all the options in the IDE to handle everytype of exception.


Solution:1

The C standard library isn't aware of C++ exception handling, so try-catch won't work. You might want to look at the matherr function - according to the documentation, you can redefine this function in your program in order to handle math exceptions by yourself.


Solution:2

Unfortunately the C math library doesn't know about C++ exceptions. Most likely you're seeing an unhandled floating point exception from your hardware. atan2 is extremely forgiving about its inputs: The only invalid case is (0, 0) so all you have to do is verify that one argument is nonzero before making the function call to prevent the exception.

EDIT: Then you need to prevent the invalid theta component when calling the function. What does the third party library documentation say about when it's valid to call theta?


Solution:3

The atan2 function should not throw an exception for arguments (0,0). See Charles Petzold's discussion here: http://www.charlespetzold.com/blog/2008/09/180741.html. So it looks as though C++ Builder's standard library is buggy.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »