1、 抛出异常
异常表示程序出现错误的信息,例如当除数为0,非法输入,数组下标越界等等,这一个错误但是C++检测不出来,幸运的是硬件会检查出来,在C++中有一个类的层次结构,异常类的基类是exception,在处理不同的异常时C++使用不同的异常类,这些异常类为exception的派生类,内存空间分配错误,就会抛出bad_alloc的异常等。
2、 处理异常
处理异常都是通过catch块实现,catch(*)中的参数*表示要捕获异常的类型,例如:
1) catch(char *e)// 异常类型为char*
2) catch(bad_alloc e) //异常类型为bad_alloc
3) catch(exception e)//捕获的异常类型为exception以及所有的exception的派生类
这里的e表示一个类的对象。
如下:
#include<iostream>
#include<exception>
using namespace std;
int abc(int a, int b, int c)
{
if (a <= 0 || b <= 0 || c <= 0)
throw "All parameters should be >0";
return a + b*c;
}
int main()
{
try{ cout << abc(1, 0, 2) << endl; }
catch (char *e)
{
cout << "The parameters is 1,0,2;" << endl;
cout << "An exception has been thrown" << endl;
cout << e << endl;
}
return 0;
}
当catch(char *e)时,为什么会抛出All parameters should be >0,对于异常在类中是如何实现的,下面将自定义异常类便于理解;
定义一个异常类illegalFunction如下:
class illegalFunction{
public:
illegalFunction() : message("参数不合法"){}
illegalFunction(char *messageInfo)
{
message = messageInfo;
}
void outputMessage(){ cout << message << endl; }
private:
string message;
};
//定义abc函数
int abc(int a, int b, int c)
{
if (a <= 0 || b <= 0 || c <= 0)
throw illegalFunction("All parameters should be >0");
return a + b*c;
}
//主函数如下
int main()
{
try{ cout << abc(1, 0, 2) << endl; }
catch (illegalFunction e)
{
cout << "The parameters is 1,0,2;" << endl;
cout << "An exception has been thrown" << endl;
e.outputMessage();
return 1;
}
return 0;
}
运行结果:
The parameters is 1,0,2;
An exception has been thrown
All parameters should be >0
其中catch(illegalFunction e)
e只是作为illegalFunctio的一个对象,e会自动的调用相关的构造函数,最后输出对应的异常结果