C ++基本字符串异常

时间:2011-07-22 17:34:50

标签: c++ exception

如果我只是想抛出一个字符串,那么某个地方是否有内置类型以便我可以做到

throw standard_exception("This is wrong!");

或者我是否必须定义这样一个标准异常,它自己来自异常?我知道这样做非常简单,我只是觉得这很常见,以至于它会在某处定义。

由于

4 个答案:

答案 0 :(得分:6)

std::runtime_errorstd::logic_error(都来自std::exception)都有构造函数,它们接受字符串并覆盖what()成员函数以返回提供的字符串。

答案 1 :(得分:6)

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

throw "I'm throwing a string!";

但这并不是一个特别好的主意,因为将char* s之类的东西视为异常并不是一种好的形式。如果您想将字符串包装成某种形式的例外,您可以随时使用runtime_errorlogic_error

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

答案 2 :(得分:4)

Runtime error应该是你要找的东西

throw runtime_error("This is wrong");

答案 3 :(得分:1)

您可以抛出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" );