【问题标题】:How to catch char * exceptions in C++如何在 C++ 中捕获 char * 异常
【发布时间】:2015-10-29 09:36:53
【问题描述】:

我试图在 main() 中捕获 char * 类型异常,但程序崩溃并显示以下消息:在抛出 'char const*' 实例后调用终止 代码如下:

#include <iostream>

int main ()
{
    char myarray[10];
    try
    {
        for (int n=0; n<=10; n++)
        {
            if (n>9)
            throw "Out of range";
            myarray[n]='a';
        }
    }
    catch (char * str)
    {
        std::cout << "Exception: " << str << std::endl;
    }
    return 0;
}

【问题讨论】:

    标签: c++ exception


    【解决方案1】:

    使用常量:

    catch (const char * str)
        {
            std::cout << "Exception: " << str << std::endl;
        }
    

    【讨论】:

    • 这其实是正确的答案。字符串文字是const,因此需要这样捕获。其他答案(关于构造和抛出 std::exception 或派生类型)的风格很好,但回答不同的问题。
    【解决方案2】:

    想抓住char*

    我不知道这个想法从何而来,字符串文字是char*它们不是

    字符串字面量是const char[N],衰减为const char*

    抓住const char*

    您的程序将被终止,因为目前您实际上没有处理您的异常!

    【讨论】:

      【解决方案3】:

      首选例外:

      try {
          for (int n=0; n<=10; n++) {
              if (n>9) throw std::runtime_error("Out of range");
              myarray[n]='a';
          }
      } catch (std::exception const& e) {
          std::cout << "Exception: " << e.what() << std::endl;
      }
      

      【讨论】:

      • 如果我尝试抛出一个 int 我也无法捕捉到它
      • 你没有回答问题。
      【解决方案4】:

      C++ 标准库提供了一个基类,专门用于声明要作为异常抛出的对象。它被称为 std::exception 并在标头中定义。该类有一个名为 what 的虚成员函数,它返回一个以空字符结尾的字符序列(char * 类型),并且可以在派生类中覆盖该函数以包含某种异常描述。

      // using standard exceptions
      #include <iostream>
      #include <exception>
      using namespace std;
      
      class myexception: public exception
      {
        virtual const char* what() const throw()
        {
          return "My exception happened";
        }
      } myex;
      
      int main () {
        try
        {
          throw myex;
        }
        catch (exception& e)
        {
          cout << e.what() << '\n';
        }
        return 0;
      }
      

      更多帮助:http://www.cplusplus.com/doc/tutorial/exceptions/

      【讨论】:

      • 你没有回答问题。
      【解决方案5】:

      你不能抛出这样的字符串,你需要创建一个对象。

      throw "Out of range" 替换为throw std::out_of_range("Out of range")

      问候,

      【讨论】:

      • 你错了。你可以扔任何你喜欢的东西。
      猜你喜欢
      • 2021-05-23
      • 2011-01-26
      • 2011-07-02
      • 2020-11-23
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多