C++异常处理例子(上)
2013-10-30 14:18
260 查看
#include <iostream>
using namespace std;
int divInt(int a,int b)
{
if (b==0)
{
throw b;
}
return a/b;
}
float divFloat(float a,float b)
{
if (b==0)
{
throw b;
}
return a/b;
}
double divDouble(double a,double b)
{
if (b==0)
{
throw b;
}
return a/b;
}
int main(int argc, const char * argv[])
{
int x=5,y=0;
float x1=5.0f,y1=0.0f;
double x2=5.5,y2=0.0;
try
{
//被检查的语句;
cout<<x<<"/"<<y<<"="<<divInt(x,y)<<endl;
cout<<x1<<"/"<<y1<<"="<<divFloat(x1, y1);
cout<<x2<<"/"<<y2<<"="<<divDouble(x2, y2);
} catch (int)//异常类型。
{
cout<<"除数为0,计算错误"<<endl;//异常处理语句
}
catch(float)
{
cout<<"除数为0,计算错误"<<endl;
}
catch(double)
{
cout<<"除数为0,计算错误"<<endl;
}
catch(...)//任意异常。
{
cout<<"其它异常"<<endl;
}
return 0;
}
using namespace std;
int divInt(int a,int b)
{
if (b==0)
{
throw b;
}
return a/b;
}
float divFloat(float a,float b)
{
if (b==0)
{
throw b;
}
return a/b;
}
double divDouble(double a,double b)
{
if (b==0)
{
throw b;
}
return a/b;
}
int main(int argc, const char * argv[])
{
int x=5,y=0;
float x1=5.0f,y1=0.0f;
double x2=5.5,y2=0.0;
try
{
//被检查的语句;
cout<<x<<"/"<<y<<"="<<divInt(x,y)<<endl;
cout<<x1<<"/"<<y1<<"="<<divFloat(x1, y1);
cout<<x2<<"/"<<y2<<"="<<divDouble(x2, y2);
} catch (int)//异常类型。
{
cout<<"除数为0,计算错误"<<endl;//异常处理语句
}
catch(float)
{
cout<<"除数为0,计算错误"<<endl;
}
catch(double)
{
cout<<"除数为0,计算错误"<<endl;
}
catch(...)//任意异常。
{
cout<<"其它异常"<<endl;
}
return 0;
}
相关文章推荐
- C++异常处理
- C++类模板做特化
- C++项目中的extern "C" {}
- C#调用C++DLL库常见问题
- 【转】C++中了类继承和调用父类的构造函数方法
- C++ 类模板
- C++函数模板
- C++ Socket编程步骤 【转】
- C++流
- C++静态成员函数小结(转)
- C++ 运算符重载
- C++与JAVA的区别
- C++使用纯虚函数完成正方形和圆形的求面积运算。
- C++虚析构函数
- C++ 运算符优先级列表
- 关于C++const关键字的一些总结<一>
- c++ 字符分割实现
- C语言中的宏定义
- C++ - Windows系统cmd窗口的输入(cin)终止符
- C++ - Windows系统cmd窗口的输入(cin)终止符