【问题标题】:How to catch substr exception?如何捕获 substr 异常?
【发布时间】:2011-05-17 15:17:45
【问题描述】:

我正在使用 substr 来生成子字符串。如何捕获 substr 异常?例如:

terminate called after throwing an instance of 'std::out_of_range'

【问题讨论】:

    标签: c++ string exception stl


    【解决方案1】:

    像这样:

    try
    {
      /// use substr
    }
    catch( std::out_of_range& exception )
    {
       // print out an error, and fail, or restart if appropriate.
    }
    

    【讨论】:

    • 你比我快 33 秒,+1 先生。
    【解决方案2】:
    try
    {
        std::string sub = mystring.substr(10,1);
    }
    catch (std::out_of_range & ex)
    {
        cout << "caught exception!" << endl;
    }
    

    【讨论】:

      【解决方案3】:

      如果它的第一个参数(子字符串的起始位置)大于它所应用的字符串的长度,则 substr 会抛出一个超出范围的异常:

      string s = "foo";
      s.substr( 1 );   // ok
      s.substr( 5 );   // exception
      

      所以显而易见的解决方案是不要在可能出现第二种情况的地方编写代码。

      【讨论】:

        猜你喜欢
        • 2017-03-14
        • 2016-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多