自定义异常类

    xiaoxiao2023-03-24  4

    #include <iostream> using namespace std; class MyArray { public: MyArray(int size); ~MyArray(); public: int & operator[](int index); int getLen(); /* 1) 抛出异常eNegative 2)index = 0 抛出异常 eZero 3)index>1000抛出异常eTooBig 4)index<10 抛出异常eTooSmall 5)eSize类是以上类的父类,*/ class eSize { public: eSize(int size) { m_size = size; } virtual void printS() { cout<<"eSize::size:"<<m_size<<endl; } protected: int m_size; }; class eNegative:public eSize { public: eNegative(int size):eSize(size) { cout<<"eNegative"<<endl; } void printS() { cout<<"eNegative::size:"<<m_size<<endl; } }; class eZero:public eSize { public: eZero(int size):eSize(size) { cout<<"eZero"<<endl; } void printS() { cout<<"eZero::size:"<<m_size<<endl; } }; class eTooBig:public eSize { public: eTooBig(int size):eSize(size) { cout<<"eTooBig"<<endl; } void printS() { cout<<"eTooBig::size:"<<m_size<<endl; } }; class eTooSmall:public eSize { public: eTooSmall(int size):eSize(size) { cout<<"eTooSmall"<<endl; } void printS() { cout<<"eTooSmall::size:"<<m_size<<endl; } }; protected: private: int *m_space; int m_size; }; MyArray::MyArray(int size) { if (size<0) { throw eNegative(size); } else if(size==0) { throw eZero(size); } else if (size>1000) { throw eTooBig(size); } else if(size<3) { throw eTooSmall(size); } m_space = new int[size]; m_size = size; } MyArray::~MyArray() { if (m_space!=NULL) { delete[] m_space; m_size = 0; } } int & MyArray::operator[](int index) { return m_space[index]; } int MyArray::getLen() { return m_size; } int main() { try { MyArray a(2); for (int i =0;i<a.getLen();i++) { a[i] = i+1; printf("a:%d\n",a[i]); } } catch (MyArray::eSize &e) { e.printS(); //cout<<e.<<endl; } catch (...) { cout<<"未知异常"<<endl; } system("pause"); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1202660.html
    最新回复(0)