Reputation: 2323
Alright, it might be a stupid question, but I will go ahead and ask anyway.
So, I was wondering, what are all the possible errors associated with std::string usage ? I know a few, for example accessing char at location greater then the std::string size in various std::string functions.
While programming what errors should I keep in mind and place checks on ?
And is there an another way to do following for example, efficiently ?
std::string s("some string.");
int i = s.find ( "." );
if ( i != std::string::npos && i + 3 < s.length ( ) ) // <<== this check is what I am talking about
s.erase ( i + 3 );
I have a program, which requires hundreds of such checks, so I was wondering, there was an another way then to do if( some_condition ) each time.
Upvotes: 0
Views: 122
Reputation: 47794
If i
greater than the string length, an out_of_range
exception is thrown
Ref:- std::string::erase
So you can always catch it !
std::string s("some string.");
int i = s.find ( "." );
if (i != std::string::npos)
try
{
s.erase ( i + 3 );
}
catch (const std::out_of_range& err)
{
std::cerr << "Out of Range error: " << err.what() << std::endl;
}
Upvotes: 0
Reputation: 385144
You don't need to list every error case for the whole class; just look up the documentation for the functions that you use, which typically lists preconditions.
For example, cppreference.com's page on std::string::erase
.
Upvotes: 2