c++ - 在运算符重载中使用 throw 来处理异常 (C++)

标签 c++ exception overloading operator-keyword throw

而且我对异常和处理知之甚少。我有一个围绕类 PolylinePoint 定义的代码。在这种情况下,点取决于折线。并且描述了运算符重载方法。由于“抛出”,我在其中一个问题上遇到了麻烦,因为我不太明白。

我的代码是:

//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/

相关文章:

c++ - 在 C++ 中可视化图形和 voronoi 图的最佳方法

.NET 4.0 WPF 自动化异常

Android加载一些数据

java - 从 List<Integer> 中正确删除整数

c++ - 如何调用 'call by value '和 'call by reference'重载函数?

c++ - 重载 QDebug::operator<< 时出现段错误

c++ - 为什么 NULL 被转换成 string*?

c++ 二维数组作为私有(private)类变量

python - Django 中的 NoReverseMatch 异常帮助

c++ - 为接受函数指针作为多种类型函数参数的函数创建模板函数