阅读量:2
C++ 标准异常类位于 头文件中,它们是继承自 std::exception 类的基类。这些异常类提供了关于错误的一般信息。以下是 C++ 标准异常类的继承结构:
class std::exception {
public:
std::exception() noexcept;
virtual ~std::exception() noexcept;
const char* what() const noexcept;
};
C++ 标准异常类包括以下几种:
std::runtime_error:表示运行时错误,通常是由程序逻辑错误引起的。它继承自std::exception类。
class std::runtime_error : public std::exception {
public:
explicit runtime_error(const std::string& message) : message_(message) {}
const char* what() const noexcept override { return message_.c_str(); }
private:
std::string message_;
};
std::logic_error:表示逻辑错误,通常是由程序中的错误条件引起的。它也继承自std::exception类。
class std::logic_error : public std::exception {
public:
explicit logic_error(const std::string& message) : message_(message) {}
const char* what() const noexcept override { return message_.c_str(); }
private:
std::string message_;
};
std::out_of_range:表示访问数组或其他容器时越界。它继承自std::runtime_error类。
class std::out_of_range : public std::runtime_error {
public:
explicit out_of_range(const std::string& message) : std::runtime_error(message) {}
};
std::bad_alloc:表示内存分配失败,通常是由于系统资源不足引起的。它继承自std::runtime_error类。
class std::bad_alloc : public std::runtime_error {
public:
const char* what() const noexcept override { return "Memory allocation failed"; }
};
std::domain_error:表示传递给函数的参数超出了其允许的范围。它继承自std::runtime_error类。
class std::domain_error : public std::runtime_error {
public:
explicit domain_error(const std::string& message) : std::runtime_error(message) {}
};
std::invalid_argument:表示传递给函数的参数无效。它继承自std::runtime_error类。
class std::invalid_argument : public std::runtime_error {
public:
explicit invalid_argument(const std::string& message) : std::runtime_error(message) {}
};
std::length_error:表示传递给函数的参数过长。它继承自std::runtime_error类。
class std::length_error : public std::runtime_error {
public:
explicit length_error(const std::string& message) : std::runtime_error(message) {}
};
std::out_of_range:表示访问数组或其他容器时越界。它继承自std::runtime_error类。
class std::out_of_range : public std::runtime_error {
public:
explicit out_of_range(const std::string& message) : std::runtime_error(message) {}
};
这些异常类都提供了一个 what() 成员函数,用于返回描述错误的字符串。当程序抛出异常时,可以通过调用 what() 函数来获取错误信息。
以上就是关于“C++标准异常类的错误信息”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm