异常处理

try catch 我们从没有仔细的研究过,还记得老师说过的一句话:自己的程序以前从来没有异常处理。

下面的两个例子作对比,一个抛出数据类型,一个抛出类对象

 

一个例子:抛出的是数据类型成员

#include<iostream>
#include<cmath>
using namespace std;

void main()
{
 double triangle(double ,double,double);
 double a,b,c;
 cin>>a>>b>>c;
 try                 //in the block of try include function which will be checked whether is reasonable
 {
  while(a>0&&b>0&&c>0)
  {
   cout<<triangle(a,b,c)<<endl;
   cin>>a>>b>>c;
  }
 }
 catch(double)                 // use catch to capture the exception and deal with it
 {
  cout<<"this is not a triangle"<<endl;
 }
  cout<<"end"<<endl;
}


double triangle(double a,double b,double c)
{
 double s=(a+b+c)/2;
 if(a+b<=c||b+c<=a||c+a<=b) throw b;//throw the exception information
 return sqrt(s*(s-a)*(s-b)*(s-c));
}

第二个例子:

#include<iostream>
#include<string>
using namespace std;


// define the exceptional class
class Excep
{
public:
 Excep():report("除数为零"){ }
 const string prdouble() const{return report;}
  
private:
 const string report;
};
//define function modal
double quotient(double numerator,double denominator);

// main function
double main()
{
 double num1,num2,result;
 cout<<"please input two figures :numeator firstly, and denominator next to it"<<endl;
 while(cin>>num1>>num2)
 {
  try   //check
  {
   result=quotient(num1,num2);
   cout<<"商"<<result<<endl;
  }
  catch(Excep ex)
  {
   cout<<"some exception happened"<<ex.prdouble()<<endl;
   system("pause");
   return 0;
  }
  cout<<"input two numbers"<<endl;
 }
 return 0;
}

//dhe difinition of the functiondouble quotient(double numerator,double denominator){ if(denominator==0)  throw Excep(); return numerator/denominator;}

相关文章
相关标签/搜索