问题:C++使用try&catch进行异常处理的简单范例
本程序通过VC++ 6.0编译与测试,要求是判断除数是否为0,这里给出了传统的if判断法和try&catch处理法,具体代码如下:
//常规方法判断除数是否为0:使用if过滤
#include <iostream>
using namespace std;
bool func(float a,float b,float &c)
{
if(b==0)
{
return false;
}
c=a/b;
return true;
}
int main()
{
float a=10,b=0,c=0;
bool result=func(a,b,c);
if(!result)
{
cout<<"the func is fail"<<endl;
return 0;
}
else
{
cout<<"the func is succeed"<<endl;
return 0;
}
}
程序运行结果:
//使用try和catch进行异常的处理
#include <iostream>
using namespace std;
void f()
{
int a=5;
int b=0;
if(b==0)
throw"错误,除数为0!"; //设置条件,抛出异常
int c=a/b; //抛出异常后后面的代码不执行
}
int main()
{
try //可能出现错误的代码放到try里面
{
f();
}
catch(char* error)//参数要和抛出的异常匹配
{
cout<<error<<endl;
}
return 0;
}
程序运行结果: