0lt
0lt

Reputation: 313

Try block continues after catch

In an overloaded operator[] function, I have the following block of code:

try {       
   if (index < 0 || index >= n)
      throw new std::out_of_range("Invalid index!");
   return arr[index];   
}   
catch(std::out_of_range& ex)  { 
   cout << ex.what() << endl;   
}

The function is called with

cout << arr[-1];

which results in an unhandled std::out_of_range exception. After inspecting the code execution, it turned out that after the throw, the execution doesn't go to the catch block, but straight to the return statement.

I don't usually catch exceptions in the same function, this was for testing purposes only and I want to understand what is going on.

Upvotes: 0

Views: 273

Answers (1)

john
john

Reputation: 87959

Not

throw new std::out_of_range("Invalid index!");

but

throw std::out_of_range("Invalid index!");

To elaborate in your code you are catching type std::out_of_range& but throwing type std::out_of_range*. And as is pointed out in the comments there's no good reason not to catch const std::out_of_range&

Upvotes: 4

Related Questions