【问题标题】:Cannot Exit Method after throwing Exception抛出异常后无法退出方法
【发布时间】:2019-04-13 02:58:56
【问题描述】:

请注意,我不太了解 throw 的工作原理。现在我有一个方法来检查一个变量是否大于或等于另一个变量,如果不是,那么它会抛出一个字符串异常。

问题是我不知道如何在抛出异常后退出方法而没有得到未处理的异常错误。

CircleSquare Square::operator+ (const Circle& op2)
{
    /// Variables
    CircleSquare ret;

    /// Sets the temporary Square object's characteristics to LHS's colour, the sum of LHS sideLength + RHS sideLength, and Square name
    ret.SetName((char *)"Square-Circle");
    ret.SetColour((char *)this->GetColour());

    if (sideLength >= (op2.GetRadius() * 2))
    {
        ret.SetSideLength(sideLength);
    }
    else
    {
        throw ("The sideLength of square is smaller than the diameter of the contained circle.");
        return ret; // <--- Here is where the error occurs
    }

    if ((op2.GetRadius() * 2) <= sideLength && op2.GetRadius() >= 0.0)
    {
        ret.SetRadius(op2.GetRadius());
    }
    else
    {
        throw ("The radius of contained circle is larger than the sideLength of the square.");
        return ret;
    }

    return ret;
}

我想要它做的是抛出异常,然后我退出方法并在我的 try-catch 块中处理异常,但是相反,它在 return ret; 处出现“未处理的异常”

如何退出此方法而不出现错误?

【问题讨论】:

标签: c++ exception throw


【解决方案1】:

你需要catch你是throwing。此外,return 语句永远不会在您 throw 时发生。 (你应该删除上面写着的行:

return ret; // <--- Here is where the error occurs

您很可能会看到一些关于编译器的警告(即永远不会执行的代码)。您的代码应该在没有警告的情况下编译。总是。 (-Werror compile flag 非常适合这个)。

throw 表示:返回但不是正常的方式

您需要执行以下操作:

try {
    Square a;
    Circle b;
    CircleSquare sum= a + b; // You try to sum
    // If you can, the return statement will give a value to sum
    // If you throw, sum will not get constructed, 
    // b and a will be destroyed and the catch 
    // will be executed instead of anything below
    // the call to operator+
    std::cout << "Sum is: " << sum << std::endl;
} catch (std::string s) {
    // Will only catch exceptions of type std::string
    std::cerr << "Error: " << s << std::endl;
}

如果你对catch 块做了一个goto,但要清理所有内容,那就“喜欢”了。

如果你不处理它,它仍然会异常终止每个函数,直到找到正确类型的catch块或直到它退出main

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多