如何在C++中捕获char *异常

6

我正在尝试在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;
}
5个回答

14

使用 const 关键字:

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

6
这实际上是正确的答案。字符串字面值是“const”,因此需要将其作为常量处理。其他关于构造和抛出std::exception或其派生类型的答案是良好的风格,但回答了不同的问题。 - Peter

4

你不想捕获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;
}

如果我试图抛出一个整数,我也无法捕获它。 - Mutai Mwiti
2
你没有回答这个问题。 - Lightness Races in Orbit

1
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/


3
你没有回答这个问题。 - Lightness Races in Orbit

-4

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

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

祝好!


5
你的误解了。你可以随意扔任何东西。 - Lightness Races in Orbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接