2

and I have a poor knowledge about exceptions and handling. I have a code defined around the class Polyline and Point. In this case, Point depends on Polyline. And there are operator overloading methods described. I'm having trouble in one of them due to the "throw" , as I don't get it very well.

My code is:

//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];
}

So, questions.

What is throw for exactly here (I know it's for give an exception for index out of range) but why use throw instead of a simple advise with cout or similar? and why don't use try?

Thanks

Paula
  • 184
  • 1
  • 3
  • 9
  • 1
    The exceptions mechanism allows programs to catch them on the appropriate level and try to address them. Printing out stuff is good, but - on its own - it will just explain why your program stopped working. ``try`` and ``catch`` are for code that *calls* code that may ``throw``. I really suggest you read a C++ book. – Ami Tavory Jun 06 '15 at 07:33
  • Hi, thanks! I did read some books and webpages, I just didn't have it clear in this code, it didn't stopped working, I just wanted to get that clearer or made it better. – Paula Jun 06 '15 at 07:50

2 Answers2

2

Here we use throw to indicate the seriousness of the error. If we had simply advised using a cout, then the program will continue execution after the statement. Using throw enables us to convey that upon occurrence of index out of bounds, no more execution of the normal function body should take place.

Not having a try-catch block shows that the function does not intend to handle index range out of bounds errors and simply transfers the program control to be handled by the catch block elsewhere.

Nivetha
  • 698
  • 5
  • 17
0

'throw' is to communicate to a calling function somewhere up the call stack that something has gone wrong and an exceptional circumstance has occurred. In a function like this, it's assumed that there is a function which will in its body take responsibility for any exceptions which arise during execution--the try block.

In other words, the throw is to indicate an error occurred. There is a try block somewhere else in the program to catch the thrown exception, or there should be, as an unhandled exception will make the program call terminate.

jaggedSpire
  • 4,423
  • 2
  • 26
  • 52
  • Hi, thanks. I understand then how throw is the correct way of indicating the error. But there is no try block in the whole program, so I got confused. – Paula Jun 06 '15 at 07:46
  • If there is no try-catch, the program will terminate. This is acceptable for many exceptions, including ones you can't (e.g., out of memory) or don't want to (e.g., out of file handles) recover from. –  Aug 30 '21 at 19:27