c++基本字符串异常
C++ basic string exception
如果我只是想抛出一个字符串,是不是有一个内置的类型,这样我就可以做
throw standard_exception("This is wrong!");
或者我必须自己定义这样一个从exception派生的标准异常吗?我知道这样做很简单,我只是认为这将是如此普遍,它将在某处定义。
谢谢
std::runtime_error
和std::logic_error
(都是从std::exception
派生的)都有构造函数接受字符串并覆盖what()
成员函数以返回所提供的字符串。
如果你想抛出一个字符串,你可以写
throw "I'm throwing a string!";
这不是一个特别好的主意,虽然,因为它不被认为是好的形式抛出像char*
s作为异常。如果你想把字符串包装成某种形式的异常,你总是可以使用runtime_error
或logic_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" );
相关文章:
- 在 c++ 中将集合转换为向量和向量转换为字符串时出现运行时异常
- std::out_of_range字符串比较中的异常
- 字符串的异常行为会追加属性 C++
- 将异常字符串解析为向量上的浮点运算?
- C++ 异常从字符串转换为c_str会创建垃圾字符
- 将 GetLastError() 转换为带有错误字符串的异常
- 在字符串类上的成员函数和out_of_range异常处理
- 尝试编写我自己的字符串类在 gcc 中出现异常
- 如何避免字符串到整数转换情况下的无效参数异常
- 由于字符串到JSON转换而产生的异常如何解决
- 异常和 C 样式字符串
- 附加性std字符串时,bad_Alloc异常
- 引发未经处理的异常:读取访问冲突。这>字符串被0x1C6F112
- 多个字符串异常处理
- boost::p rogram_option::store 在选项字符串包含混合语言字符时引发异常
- 如何通过包含要打印的字符串的类函数打印异常
- 关于多线程应用程序中的 STL 字符串异常
- 字符串转换错误:异常还是错误代码
- std::out_of_range在字符串向量中搜索匹配项时发生异常
- 将值分配给字符串向量时的 Cygwin 异常