【发布时间】:2015-06-06 07:28:08
【问题描述】:
我对异常和处理知之甚少。我有一个围绕类 Polyline 和 Point 定义的代码。在这种情况下,Point 取决于 Polyline。并且描述了运算符重载方法。由于 "throw" ,我在其中一个中遇到了麻烦,因为我不太明白。
我的代码是:
//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?
谢谢
【问题讨论】:
-
异常机制允许程序在适当的级别捕获它们并尝试解决它们。打印出来的东西很好,但是——就其本身而言——它只会解释你的程序为什么停止工作。
try和catch用于调用可能throw的代码。我真的建议你读一本 C++ 书。 -
您好,谢谢!我确实阅读了一些书籍和网页,但我只是在这段代码中没有明确,它并没有停止工作,我只是想让它更清晰或更好。
标签: c++ exception overloading operator-keyword throw