我怎样才能执行不同的捕获量,具体取决于我在哪个方面?

问题描述 投票:-2回答:1

我重载了一个运算符,以便我可以返回一个数组的值。我可以使用if处理越界:

float arr::operator[](const int i) const
{
    if (i < 0)
    {
        cout << "Outside of array, first entry returned" << endl;
        return value[0];
    }

    else if (i >=size)
    {
        cout << "Outside of array, last entry returned"  << endl;
        return value[size-1];
    }

    else return value[i];
}

但我正在学习异常和try-catch块。

是否可以使用不同的int(例如)为超出上限/下限抛出异常,并且具有执行不同代码的捕获,具体取决于该int的值?

我知道if在这里运作良好,但我希望发展我的知识,用于更复杂的想法。

c++ exception try-catch
1个回答
4
投票

是否可以使用不同的int(例如)为超出上限/下限抛出异常,并且具有执行不同代码的捕获,具体取决于该int的值?

有点。您当然可以根据条件抛出不同的int值,但是您必须捕获单个通用int并测试其值,您无法单独捕获不同的int值。例如:

const int OutOfBoundsInFront = -1;
const int OutOfBoundsInBack = 1;

float arr::operator[](const int i) const
{
    if (i < 0)
        throw OutOfBoundsInFront;

    if (i >= size)
        throw OutOfBoundsInBack;

    return value[i];
}

...

try
{
    ... = myarr[index];
}
catch (int value)
{
    switch (value)
    {
        case OutOfBoundsInFront:
            //...
            break;

        case OutOfBoundsInBack:
            //...
            break;
    }
}

但是,抛出异常时,最好抛出一个对象而不是简单的POD类型。 catch阻止类型的交易,而不是价值。在这种情况下,您可以为要捕获的每个条件定义不同的类类型。例如:

#include <stdexcept>

class OutOfBoundsInFront : public std::out_of_range
{
public:
    OutOfBoundsInFront() : std::out_of_range("out of bounds in front") {}
};

class OutOfBoundsInBack : public std::out_of_range
{
public:
    OutOfBoundsInBack() : std::out_of_range("out of bounds in back") {}
};

float arr::operator[](const int i) const
{
    if (i < 0)
        throw OutOfBoundsInFront();

    if (i >= size)
        throw OutOfBoundsInBack();

    return value[i];
}

...

try
{
    ... = myarr[index];
}
catch (const OutOfBoundsInFront &)
{
    //...
}
catch (const OutOfBoundsInBack &)
{
    //...
}

或者:

#include <stdexcept>

class OutOfBoundsOnSide : public std::out_of_range
{
public:
    enum WhichSide { InFront, InBack };

    static const char* WhichSideErrorMsg[] = {
        "out of bounds in front",
        "out of bounds in back"
    };

    WhichSide whichSide;

    OutOfBoundsOnSide(WhichSide side) : std::out_of_range(WhichSideErrorMsg[side]), whichSide(side) {}
};

class OutOfBoundsInFront : public OutOfBoundsOnSide
{
public
    OutOfBoundsInFront() : OutOfBoundsOnSide(InFront) {}
};

class OutOfBoundsInBack : public OutOfBoundsOnSide
{
public
    OutOfBoundsInBack() : OutOfBoundsOnSide(InBack) {}
};

float arr::operator[](const int i) const
{
    if (i < 0)
        throw OutOfBoundsInFront();

    if (i >= size)
        throw OutOfBoundsInBack();

    return value[i];
}

...

try
{
    ... = myarr[index];
}
catch (const OutOfBoundsOnSide &e)
{
    switch (e.whichSide)
    {
        case InFront:
            //...
            break;

        case InBack:
            //...
            break;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.