1

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?

2
  • (Never mind. I see you're not really coding in Qt.) Commented Aug 8, 2011 at 21:03
  • @Daniel R Hicks I am using C++ object in a Qt C++ project. Commented Aug 8, 2011 at 21:59

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

11 Comments

as it's stated in cplusplus.com/reference/string/string/at : If the position passed is past the end of str, an out_of_range exception is thrown.
@vines: What's that got to do with my answer?
But the position passed isn't "past the end of str", it's negative.
Is it negative or an unsigned large value?
string::at(size_t), where size_t is (obviously) unsigned. @Kerrek SB: it has to do the following: why there's (supposedly) no exception where it should be?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.