异常处理就是处理程序中的错误,错误就是程序在运行期间发生的一些异常事件,(栈溢出,转换失败,数组下标越界等)。
2、异常的语法3、异常处理实例throw:抛出异常 , 代替return语句
try //检查可能发生异常的语句
{
...........
}
catch //铺获异常
{
...........
}
除0自然会产生异常
#include4、异常的思想using namespace std; int Div(int x,int y) { if(0 == y) { throw 0; //抛出异常 } return x / y; } int main(int argc, char const *argv[]) { int a,b; cin >>a>>b; try //把可能发生异常的语句放在try语句中 { cout<
#include5、异常的声明using namespace std; int Div(int x,int y) { return DDiv(x,y); } int DDiv(int x,int y) { if(0 == y) { //throw 0; //抛出异常 throw 'a'; //抛出异常 } return x / y; } int main(int argc, char const *argv[]) { int a,b; cin>>a>>b; try { cout<
#include6、异常对象using namespace std; //int Div(int x,int y); //可能抛出任何异常 //int Div(int x,int y) throw(int,char); //只能输出int,char类型的异常 int Div(int x,int y) throw(); //不会输出任何异常 int main(int argc, char const *argv[]) { int a,b; cin>>a>>b; try { cout<
#includeusing namespace std; class Test { public: Test() { cout<<"Test的构造函数"< >a>>b; try { cout 7、标准异常库 c++提供了一组标准异常类,这些类以基类exception开始,标准程序库中抛出的所有异常都派生于该基类
virtual const char *what() const throw() = 0;
//exception 提供的一个虚函数 what() 用来返回错误信息
exception--->bad_alloc, bad_cast, bad_typeid, over_flow, logic_error
//bad_alloc : new 或者 new[ ] 分配内存失败抛出异常
//bad_cast : dynamic_cast 转换失败抛出异常
//bad_typeid : typeid 操作空指针,而且该指针带有虚函数的类,抛出异常
//over_fiow: 计算错误(上溢),抛出异常
//logic_error :逻辑错误,有派生类 out_of_range 超出有效范围
#include#include using namespace std; int func(int *a,int index) { if(index > 2) { throw out_of_range("index不能小于2"); } } int main(int argc, char const *argv[]) { int a[3] = {1,2,3}; try { func(a,10); } catch(const std::exception& e) { cout<



