How to catch substr exception?
I'm using substr for generating substring. How I can catch substr exception? For instance:
terminate called after throw开发者_如何学Cing an instance of 'std::out_of_range'
Like this:
try
{
/// use substr
}
catch( std::out_of_range& exception )
{
// print out an error, and fail, or restart if appropriate.
}
try
{
std::string sub = mystring.substr(10,1);
}
catch (std::out_of_range & ex)
{
cout << "caught exception!" << endl;
}
substr throws an out of range exception if its first parameter (the starting position of the substring) is greater than the length of the string it is being applied to:
string s = "foo";
s.substr( 1 ); // ok
s.substr( 5 ); // exception
So the obvious solution is not to write code where the second case can occur.
精彩评论