C++错误机制:
/-----------------------------------------------------------------------------------/
"调用abort()"
如果这么做 程序直接爆炸:
#include <iostream>
using namespace std;
double Div( int nLeft, int nRight )
{
if( nRight == 0 )
{
cout << "Error" << endl;
abort();
}
else
{
return static_cast< double > ( nLeft ) / static_cast< double > ( nRight );
}
}
int main( int argc, char *argv[] )
{
cout << Div( 5, 0 );
return 0;
}
/-----------------------------------------------------------------------------------/
"函数返回值"
在函数中加入参数返回逻辑结果 然后函数设置为bool返回值 设置为是否异常;
#include <iostream>
#include <float.h>
using namespace std;
bool Div( int nLeft, int nRight, double &ans )
{
if( nRight == 0 )
{
ans = DBL_MAX;
return false;
}
else
{
ans = static_cast< double > ( nLeft ) / static_cast< double > ( nRight );
return true;
}
}
int main( int argc, char *argv[] )
{
double dAns;
if( Div( 5, 0, dAns ) )
{
cout << dAns << endl;
}
else
{
cout << "Error" << endl;
}
return 0;
}
/-----------------------------------------------------------------------------------/
"异常机制"
try throw catch 机制;
try 表示这一块代码可能会引发异常 要注意这块代码
当try块内的代码发生异常的时候 我们应该抛出 throw 这个异常,
之后这个异常会被 catch 接收到 然后 catch 内即为我们的处理代码;
( 在catch块内 里面的 const int error 可以被匹配为int 我们也可以设置两个catch块 另一个匹配 const char* ch )
#include <iostream>
#include <float.h>
using namespace std;
#define ERROR_ONE 1
#define ERROR_TWO 2
double Div( int nLeft, int nRight )
{
if( nRight == 0 )
{
throw ERROR_ONE;
}
else if( nLeft == 0 )
{
throw ERROR_TWO;
}
else
{
return static_cast< double > ( nLeft ) / static_cast< double > ( nRight );
}
}
int main( int argc, char *argv[] )
{
double dAns;
int nLeft, nRight;
while( cin >> nLeft >> nRight )
{
try
{
dAns = Div( nLeft, nRight );
}
catch( const int error )
{
switch( error )
{
case ERROR_ONE:
cout << "Error_one";
break;
case ERROR_TWO:
cout << "Error_two";
break;
}
continue;
}
cout << dAns;
}
return 0;
}