我使用substr來生成子字符串。我如何捕獲substr異常?例如:如何捕獲substr異常?
terminate called after throwing an instance of 'std::out_of_range'
我使用substr來生成子字符串。我如何捕獲substr異常?例如:如何捕獲substr異常?
terminate called after throwing an instance of 'std::out_of_range'
像這樣:
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引發超出範圍的異常,如果它的第一個參數(子串的起始位置)比串的長度大它適用於:
string s = "foo";
s.substr(1); // ok
s.substr(5); // exception
因此,顯而易見的解決方案是不寫代碼的第二種情況下可以發生。
你打我33秒,先生+1。 – 2011-05-17 15:22:24