|
我想编一个能在Windows和Linux下运行的数学计算程序,可是在编写异常时出现了问题。以下这个程序能在Visual C++6.0和Dev-c++(gcc的windows版本)上运行。Visual C++6.0可以捕获数学计算的异常,但Dev-c++却没能抓上一个。
c++程序:
Little Change From microsoft Company MSDN
[php]
// Floating-point exception class sample
// Compile Options /GX
/*******************************************************************
This program demonstrates how to use the exception classes
from the diagnostics library to handle floating point exceptions;
float_error class is derived from logic_error base class.
********************************************************************/
//#include <exception>
#include <stdexcept>
#include <cmath>
#include <iostream>
#include <complex>
using namespace std;
//floating-point exception class
class float_error : public logic_error
{
public:
float_error (char buffer[]) : logic_error (buffer)
{
cout <<"Floating point math error occurred in your program ";
cout <<"More details below:"<<endl;
}
};
//Math error handler
int _matherr (struct _exception * ex)
{
char buffer [128];
const char * ErrorType;
//Determine type of error.
cout<<"Ex type is: "<<ex->type<<endl;
switch (ex->type)
{
case _DOMAIN:
ErrorType = "Domain Error: ";
break;
case _SING:
ErrorType = "Singularity Error:";
break;
case _OVERFLOW:
ErrorType = "Overflow Error:";
break;
case _UNDERFLOW:
ErrorType = "Underflow Error:";
break;
case _PLOSS:
ErrorType = " artial Loss of significance:";
break;
case _TLOSS:
ErrorType = "Total loss of significance:";
break;
default:
ErrorType = "Some other math error:";
}
//Construct error string.
sprintf (buffer, "%s: %s(%g,%g) returns %g",ErrorType,
ex->name,ex->arg1,ex->arg2,ex->retval);
//Throw an exception.
throw float_error(buffer);
return 0;
}
void TestMathErrors(double (*fp) (double), double arg)
{
//Next text
bool caught = false;
//Generate a floating-point error.
try {
double x = fp (arg);
cout<<"x is: "<<x<<endl;
}
catch (exception & ex)
{
cout << ex.what() << endl<<endl;
caught = true;
}
if (!caught)
cout << "didn't catch exception through materr\r\n";
}
int main ()
{
typedef double (*fp) (double);
//Array to the several functions
fp math_function [] = { &sqrt, &log, &sin, &tan, &acos };
double arg []= { -1.0, 0.0, 1.5e25, 1.5e25, 2 };
for (int n=0; n < 5;n++)
TestMathErrors(math_function[n],arg[n]);
system(" AUSE");
return 0;
}
[/php] |
|