请注意,我真的不明白投掷是如何运作的。现在我有一个方法来检查一个变量是否大于或等于另一个变量,如果不是,那么它会抛出一个字符串异常。
问题是我不知道如何在抛出异常后退出方法而不会得到未处理的异常错误。
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;
上出现了“Unhandled Exception”
如何在不收到错误的情况下退出此方法?
你需要catch
你是什么throw
ing。此外,当你return
时,throw
声明永远不会发生。 (你应该删除说:
return ret; // <--- Here is where the error occurs
最有可能的是,你会看到编译器的一些警告(这是永远不会被执行的代码)。您的代码应该编译而不会发生警告。总是。 (-Werror
编译标志对此非常好)。
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;
}
如果你对goto
区块做了一个catch
,那就是“喜欢”,但清理一切。
如果你不处理它,它仍会异常终止每个函数,直到它找到一个正确类型的catch
块或直到它退出main
。