C++ exception return type why char*

我的梦境 提交于 2021-02-16 17:57:22

问题


Could someone explain why self-written C++ exception, that inherit from exception return a char * and not a string?

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

Source : http://www.cplusplus.com/doc/tutorial/exceptions/


回答1:


Since std::exception was designed as a base class for all exceptions, the interface is written in such a way that specializations do not require code that may throw. They may use it, but they do not require it to implement the interface.

If the base exception class required std::string for example, then std::out_of_memory could not inherit from it (because constructing a string to pass into the constructor may not work after the runtime has already encountered an out-of-memory condition).

The construction of the class based exclusively on POD types, allows the implementation of std::out_of_memory (and probably other exceptions that get created in extraordinary circumstances) as a specialization.

That doesn't mean that you cannot use std::string (or anything else) in your exceptions. In fact, most exceptions in practice are derived from std::logic_error and std::runtime_error, both of which take in a std::string argument.

Note: Unless you really need this, consider inheriting your base exception class from std::runtime_error or std::logic_error. They are higher level and inheriting from std::exception directly is more than most cases require.




回答2:


myexception is inherited from std::exception class which defines this virtual method http://en.cppreference.com/w/cpp/error/exception/what:

virtual const char* what() const;

You cannot change signature of virtual function in derived class. std::exception has such signature because std::string constructor can throw exception itself and that will lead to disaster.



来源:https://stackoverflow.com/questions/27404680/c-exception-return-type-why-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!