【问题标题】:C++ exception return type why char*C++ 异常返回类型为什么是 char*
【发布时间】:2015-02-08 20:44:36
【问题描述】:

有人能解释为什么自写的 C++ 异常,继承自异常返回一个 char * 而不是一个字符串?

class myexception: public exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
} myex;

来源:http://www.cplusplus.com/doc/tutorial/exceptions/

【问题讨论】:

  • 覆盖std::exceptionwhat()

标签: c++ string pointers exception char


【解决方案1】:

由于 std::exception 被设计为所有异常的基类,因此接口的编写方式使得专门化不需要可能抛出的代码。他们可以使用它,但不需要它来实现接口。

例如,如果基异常类需要std::string,则 std::out_of_memory 不能从它继承(因为在运行时已经遇到内存不足后,构造要传递给构造函数的字符串可能无法工作条件)。

仅基于 POD 类型的类的构造允许将 std::out_of_memory (以及可能在特殊情况下创建的其他异常)实现为特化。

这并不意味着您不能在异常中使用 std::string (或其他任何东西)。事实上,实践中的大多数异常都是从 std::logic_error 和 std::runtime_error 派生的,它们都接受一个 std::string 参数。

注意:除非你真的需要这个,否则考虑从 std::runtime_error 或 std::logic_error 继承你的异常基类。它们更高级别,直接从 std::exception 继承比大多数情况需要的更多。

【讨论】:

  • 完全同意你的意见。几乎所有用户异常都是某种形式的runtime_error(由于文件或套接字等外部状态不可用)或logic_error(程序逻辑错误,必须更正 - 例如前提条件检查失败)。
【解决方案2】:

myexception 继承自 std::exception 类,该类定义了此虚拟方法 http://en.cppreference.com/w/cpp/error/exception/what

virtual const char* what() const;

您不能更改派生类中虚函数的签名。 std::exception 有这样的签名,因为 std::string 构造函数可以自己抛出异常,这将导致灾难。

【讨论】:

    猜你喜欢
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2019-12-09
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多