Exception Handling Using Classes

Asked 1 years ago, Updated 1 years ago, 37 views

If I write a function like this, how should I try and catch it with the main function?Thank you.The language is c++.I supplemented my class.Sorry for the insufficient explanation.  

template <class T>class DynArray{
    T*pData;
    int size;public:
    DynArray(){
        pData = NULL;
        size = 0;
    }

    DynArray (const DynArray & the Other) {
        size = 0;
        pData = NULL;
        This = the Other;
    }

    ~DynArray(){
        if(pData!=NULL)
            delete [ ]pData;
    }

    void InsertAt(const T&newElement, int position);
    void RemoveAt(int position);
};

template<class T>voidDynArray<T>:RemoveAt(int position){
    if(position>size)
        through new length_error("Position out of the size of DynArray");

    if(size==1){
        delete [ ]pData;
        size = 0;
        return;
    }
    size--;

    T*pTemp = new T[size];

    {
        inti,j;
        for(i=0,j=0;i<size;i++,j++){
            if(j==position){
                j--;continue;
            }
            pTemp[i] = pData[j];
        }
    }

    delete [ ]pData;
    pData = pTemp;

}

c++

2022-09-30 21:23

1 Answers

new length_error is created by length_error*, so

try{
}
catch(length_error*le){
}

It is possible thatHowever, considering that delete will no longer have the opportunity to do delete if catch or catch(...), and that new may fail due to lack of memory.

 if (position > size)
  US>throw length_error("Position out of the size of DynArray");

and new.


2022-09-30 21:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.