而且我对异常和处理知之甚少。我有一个围绕类 Polyline 和 Point 定义的代码。在这种情况下,点取决于折线。并且描述了运算符重载方法。由于“抛出”,我在其中一个问题上遇到了麻烦,因为我不太明白。
我的代码是:
//defining the operator overloading method for []
Point & Polyline::operator[](int index) const {
//defining the exception (why don't use "try"?)
if (index >= num) {
throw out_of_range("Index out of range");
}
// if everythings OK, it returns the object reference
return p[index];
}
那么,问题。
这里的 throw 到底是什么意思(我知道它是为了给出超出范围的索引的异常)但是为什么使用 throw 而不是使用 cout 或类似的简单建议?为什么不使用 try 呢?
谢谢
最佳答案
这里我们用 throw 来表示错误的严重性。如果我们只是建议使用 cout,那么程序将在该语句之后继续执行。使用 throw 使我们能够传达这样的信息:一旦发生索引越界,就不应再执行正常的函数体。
没有 try-catch block 表明该函数无意处理索引范围越界错误,而只是将程序控制转移到其他地方由 catch block 处理。
关于c++ - 在运算符重载中使用 throw 来处理异常 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30680168/