C++ 异常处理方式并不是靠设定返回值,而是使用try ,catch
throw。
throw: 在设定出错处理的地方通过使用 throw 关键字来完成的。
catch: catch 关键字用于捕获异常。一般用来输出错误信息
try: try 块中的代码就是执行包含throw部分的代码。
#include <iostream>
using namespace std;
class Chu
{
public:
Chu(int a=0,int b=0)
{
this->a=a;
this->b=b;
}
double div(int a, int b)
{
if(b==0)
{
throw "被除数为0";
}
return a/b;
}
private:
int a,b;
};
int main()
{
Chu a;
double z;
try
{
z=a.div(2,1);
cout<<z<<endl;
}
catch(const char *msg)
{
cerr << msg<< '\n';
}
}
//下面是函数原型
/*try
{
// 程序执行代码
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
}*/