参考博客:https://blog.csdn.net/xueluowutong/article/details/81257654
一、在C++中有自身定位错误的一种方式,常用的是使用try catch
以下就是介绍一下try...catch的简单的用法:
#include <stdlib.h>
#include "iostream"
using namespace std;
double fuc(double x, double y) //定义函数
{
if (y == 0)
{
throw y; //除数为0,抛出异常
}
return x / y; //否则返回两个数的商
}
int main()
{
double res;
try //定义异常
{
res = fuc(2, 3);
cout << "The result of x/y is : " << res << endl;
res = fuc(4, 0); //出现异常
}
catch (double) //捕获并处理异常
{
cerr << "error of dividing zero.\n";
exit(1); //异常退出程序
}
while (1);
return 0;
}