C++ 标准异常类位于 头文件中,它们是 C++ 异常处理机制的基础。以下是 C++ 标准异常类的文档说明:
1. std::exception
std::exception 是所有标准异常类的基类。它提供了一个虚函数 what(),用于返回异常的描述信息。
class exception {
public:
virtual ~exception() noexcept;
virtual const char* what() const noexcept;
};
2. std::runtime_error
std::runtime_error 是一个派生自 std::exception 的异常类,用于表示运行时错误。
class runtime_error : public exception {
public:
explicit runtime_error(const string& msg) : message(msg) {}
const char* what() const noexcept override { return message.c_str(); }
private:
string message;
};
3. std::logic_error
std::logic_error 是另一个派生自 std::exception 的异常类,用于表示逻辑错误。
class logic_error : public exception {
public:
explicit logic_error(const string& msg) : message(msg) {}
const char* what() const noexcept override { return message.c_str(); }
private:
string message;
};
4. std::out_of_range
std::out_of_range 是一个派生自 std::runtime_error 的异常类,用于表示访问容器时元素超出范围的错误。
class out_of_range : public runtime_error {
public:
explicit out_of_range(const string& msg) : runtime_error(msg) {}
};
5. std::bad_alloc
std::bad_alloc 是一个派生自 std::runtime_error 的异常类,用于表示内存分配失败的错误。
class bad_alloc : public runtime_error {
public:
bad_alloc() : runtime_error("Memory allocation failed") {}
};
6. std::exception_ptr
std::exception_ptr 是一个指针类型,用于表示一个可能已经抛出但未被捕获的异常。它可以在异常处理程序之间传递异常。
class exception_ptr {
public:
// 构造函数和析构函数
// ...
// 将异常指针转换为 std::exception*
operator std::exception*() const noexcept;
// 从 std::exception* 转换回 exception_ptr
exception_ptr& operator=(std::exception* p) noexcept;
// 重新抛出存储的异常
void rethrow() const;
};
7. 其他异常类
除了上述标准异常类外,C++ 标准库还提供了许多其他异常类,如 std::domain_error、std::invalid_argument、std::length_error 等,它们都派生自 std::runtime_error 或 std::logic_error。
使用示例
以下是一个使用 C++ 标准异常类的示例:
#include
#include
int main() {
try {
throw std::runtime_error("An error occurred");
} catch (const std::runtime_error& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
以上就是关于“C++标准异常类的文档说明”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm