【发布时间】: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; 处出现“未处理的异常”
如何退出此方法而不出现错误?
【问题讨论】:
-
minimal reproducible example 会有所帮助。
return不会发生,因为throw解开了麻袋。