小白、教你学C++(8)异常处理结构层次

xiaoxiao2021-02-27  176

++++++++++++++++++++++++++++ C++处理错误的机制类型 1、 内存分配错误 2、向上溢出,乡向下溢出 范围超出 错误总类3、错的类型转换 4、逻辑错误 :超出范围、长度超出等 5、语法错误 例子: if(age>444) { throw out_of_range("年龄不合理"); //函数是编译器自带的 } C++的异常层次结构 本例子主要实现的功能就是,仿真编译器原理 输入一个数字,在和一个数组比较,如果大于零,小于零,触发 编辑好的指定异常。 #include <iostream> using namespace std; class MyArray { public: MyArray(int len); ~MyArray(int len); int &Operator[](int index); int get(int len;) private: int *m_space; int m_len; } class eSize //定义一个父类因为后面有太多的子类,为了提高效率就设计了一个虚函数继承 { public : eSize(int size); { m_size =size; } virtual void printErr(){ //打印函数 { printf("size:")<<size<<m_size<<endl;; } } class eNegative :public eSzie //子类一小于零 { public: eNegative(int size):eSize { } virtual void printErr(){ { cout<<"eNegative"<<e.eSize<<endl; } } }; cladd eTooBig :public eSzie //大于数组的容量 { eTooBig(int size):eSize { } virtual void printErr(){ { cout<<"eTooBig"<<e.eSize<<endl; } } }; class eTooSmall :public eSzie //容量太小 { eTooSmall(int size):eSize { } virtual void printErr(){ { cout<<"eTooBig"<<e.eSize<<endl; } } }; class eSize :public eSzie //公共类的函数类 { eSize (int size):eSize { } virtual void printErr(){ { cout<<"eSize "<<e.eSize<<endl; } } }; MyArray::~MyArray() { if(len<0) //抛出异常一 { throw eNegative(); } if (len==0) //抛出异常二 { throw eZero(); } else if(len>1000) //抛出异常 { throw EtooBIG(); } else if(len<3) //抛出异常 { throw eTooSmall(); } if (m_space !=NULL;) { delete[] m_space ; m_space =Null; m_len =0; } } MyArray::MyArray(int len) { m_len =len; m_space =new int[len]; } int &MyArray::operator[](int index) { return m_space[index]; } int MyArray::get() { return m-len; } void main() { try { MyArray a(-5); } for (int i=0;i<a.get();i++) { a[i] =i+1; printf("%d",a[i]); } catch (...) { } /*catch (MyArray::eNegative e //有错误) { cout <<"eNative类型错误"<<endl; }*/ catch (MyArray::eSize &e) { //cout << "len 的大小"<<e.eSize<<endl; // e.printErr(); //多态的调用 } catch () { } catch () { } cout<<"heloo..."<<endl; system("pause"); return; }
转载请注明原文地址: https://www.6miu.com/read-16470.html

最新回复(0)