Reputation: 195
Here is a snippet of the code that creates a run time error "Microsoft Visual C++ Runtime Library" http://www.flickr.com/photos/66130188@N07/6023459646/
string text = something;
size_t index = text.find("hoopla");
try{
if(text.at(index-1)<'0'&&text.at(index-1)>'9')
return false;
}catch(out_of_range){return true;}
I am running it in Qt creator. It is not triggering the catch block. When the program reaching the text.at(index-1) and index-1 is out of bounds, it creates the run time error in Qt http://www.flickr.com/photos/66130188@N07/6023453724/
I did not have a problem when I used MVS2010. Any suggestions?
Upvotes: 1
Views: 520
Reputation: 477228
You can avoid the exception check entirely by simply checking the return value of find
first:
if ((index == std::string::npos || index == 0) ||
(text[index - 1] < '0' && text[index - 1] > '9') )
{
return false;
}
In the first case, npos
, the search string wasn't found, and in the second case it is right at the beginning of the ambient string so you cannot look at the character before it.
(This is called "offensive programming": Don't check for errors at runtime, but construct your algorithm so that you know that your access is correct. If you will, you can add an assertion assert(index < text.length());
to express your certainty that you are holding a correct value, which will not weigh down your release version.)
Update: Replaces .at()
by []
since we're sure of ourselves.
Upvotes: 1