c++基本字符串异常

C++ basic string exception

本文关键字:异常 字符串 c++      更新时间:2023-10-16

如果我只是想抛出一个字符串,是不是有一个内置的类型,这样我就可以做

throw standard_exception("This is wrong!");

或者我必须自己定义这样一个从exception派生的标准异常吗?我知道这样做很简单,我只是认为这将是如此普遍,它将在某处定义。

谢谢

std::runtime_errorstd::logic_error(都是从std::exception派生的)都有构造函数接受字符串并覆盖what()成员函数以返回所提供的字符串。

如果你想抛出一个字符串,你可以写

throw "I'm throwing a string!";

这不是一个特别好的主意,虽然,因为它不被认为是好的形式抛出像char* s作为异常。如果你想把字符串包装成某种形式的异常,你总是可以使用runtime_errorlogic_error:

throw logic_error("This is wrong!");
throw runtime_error("This is wrong!");

运行时错误应该是您正在寻找的

throw runtime_error("This is wrong");

你可以抛出std::runtime_error或者创建你自己的继承自std::exception的类,如下所示

#include <exception>
#include <string>

class myexcept : public std::exception
{
private:
  /**
   * Reason for the exception being thrown
   */
  std::string what_;
public:
  /**
   * Class constructor
   *
   * @param[in] what
   *    Reason for the exception being thrown
   */
  myexcept( const std::string& what ) : what_( what ){};

  /**
   * Get the reason for the exception being thrown
   *
   * @return Pointer to a string containing the reason for the exception being thrown
   */
  virtual const char* what() const throw() { return what_.c_str(); }

  /**
   * Destructor 
   */
  virtual ~myexcept() throw() {}
};

,

throw myexcept( "The reason goes here" );