您的位置:首页 > 编程语言 > C语言/C++

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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: