C++异常



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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值