测试"Try and Catch"

testing "Try and Catch"

本文关键字:Catch and Try 测试      更新时间:2023-10-16

在这个程序中,我使用模板类,我有一个头文件,这是我的主文件。我在显示(".....")IndexOutOfBounds并在屏幕上显示它时遇到了麻烦。

#include "XArray.h"
#include <iomanip>
#include <string>
using namespace std;

template<class T>
void afriend ( XArray<T> );

int main()
{
XArray<double> myAD(18);
myAD.randGen(15, 100);
cout << myAD.getType() << endl;
cout << setprecision(1) << fixed << "nn Unsorted:     " << myAD;
myAD.sort();
cout << "n Now Sorted:     " << myAD;
cout << "nn";
**try
{
    cout << "A[-5]      = " << setw(6) << myAD[-5] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
    e.print();
}
try
{
    cout << "A[8]       = " << setw(6) << myAD[8] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
    e.print();
}**

cout << "nn" << setprecision(2) << fixed;
cout << "Size               = " << setw(6) << myAD.getSize() << endl;
cout << "Mean               = " << setw(6) << myAD.mean() << endl;
cout << "Median             = " << setw(6) << myAD.median() << endl;
cout << "STD                = " << setw(6) << myAD.std() << endl;
cout << "Min #              = " << setw(6) << myAD.min() << endl;
cout << "Max #              = " << setw(6) << myAD.max() << endl;

return 0;
}

有一个Array.h文件作为dropbox的链接

Array.h

Array.h中operator[]的代码为:

template <class T>
T XArray<T>::operator[] (int idx)
{
    if( (idx = 0) && (idx < size) )
    {
        return Array[idx];
    }
    else
    {
        throw IndexOutOfBound();
        return numeric_limits<T>::epsilon();
    }
}

虽然这个问题有点晦涩,但请尝试一下这些建议。

首先,XArray<>::IndexOutOfBounds可能没有合适的复制因子。您可以尝试通过const引用捕获以解决以下问题:

try
{
    ...
}
catch(const XArray<double>::IndexOutOfBound& e)
{
    e.print();
}
标准库容器中的

索引操作符不检查边界,有一个特殊的getter来检查称为at()。如果XArray类在设计时考虑了标准库,它的行为可能类似。

然而,为了得到更充分的回应,你需要更具体地描述你所遇到的麻烦。

我仍然想知道确切的问题是什么。然而,我理解的问题是,我如何使用'IndexOutOfBound'来使用'catch'。

#include <exception>
#include <iostream>
using namespace std;
template <typename T>
class Array
{
private:
    int m_nLength;
    T *m_ptData;
public:
...
...
    T& operator[](int nIndex)
    {
        //assert(nIndex >= 0 && nIndex < m_nLength);
        if(nIndex < 0 || nIndex > m_nLength)
        {
            throw myex;
        }
        else
        {
            return m_ptData[nIndex];
        }
    }
    //class definition for 'IndexOutOfBound'
    class IndexOutOfBound: public exception
    {
    public:
        virtual const char* print() const throw()
        {
            return "Exception occured 'Index Out Of Bound'";
        }
    }myex;
};
int main()
{
    Array<double> arr(3);
    try
    {
        arr[0] = 1;
        //exception will occur here.
        arr[4] = 2;
    }
    catch(Array<double>::IndexOutOfBound &e)
    {
        cout << e.print() << 'n';
    }

    return 0;
}

这里没有'XArray.h',所以我编写了一个示例数组类。

问题在于operator[]函数。代码idx = 0idx设置为0。因此,所有对operator[]的调用都将返回第一个元素,因此除非数组为空,否则不会出现越界错误。

你可能想写if ( idx >= 0 && idx < size )

BTW throw终止函数,throw之后的return没有意义。