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

c++异常处理机制 (try—throw—catch的使用)

2015-03-02 17:56 337 查看
try ,catch 形式如下:

try
{
可能出现错误的语句块;
}

catch (类型名[形参名])
{

}
</pre><p></p><p>实例:</p><p></p><p><pre name="code" class="cpp">#include <iostream>
#include <stdlib.h>

using std::cout;
using std::cin;
using std::endl;

double fuc(double a, double b)//定义函数;
{

if (  b == 0)// 如果除数为零,抛出异常;
throw b;
return a / b;//无异常就返回商;
}

int main(void)
{
try
{
double res;
res = fuc(4, 2);
cout << "res=" << res;
cout <<endl;
double resu = fuc(2,0);
cout << resu;
}
catch (double)//捕捉异常;
{
cout<<"数据有误!";
exit(1);  //
}
cout <<endl;
system("pause");
return 0;

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