C++ 标准异常类位于 <exception> 头文件中,它们是 C++ 异常处理机制的基础。以下是 C++ 标准异常类的文档说明:
std::exceptionstd::exception 是所有标准异常类的基类。它提供了一个虚函数 what(),用于返回异常的描述信息。
class exception {
public:
virtual ~exception() noexcept;
virtual const char* what() const noexcept;
};
std::runtime_errorstd::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;
};
std::logic_errorstd::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;
};
std::out_of_rangestd::out_of_range 是一个派生自 std::runtime_error 的异常类,用于表示访问容器时元素超出范围的错误。
class out_of_range : public runtime_error {
public:
explicit out_of_range(const string& msg) : runtime_error(msg) {}
};
std::bad_allocstd::bad_alloc 是一个派生自 std::runtime_error 的异常类,用于表示内存分配失败的错误。
class bad_alloc : public runtime_error {
public:
bad_alloc() : runtime_error("Memory allocation failed") {}
};
std::exception_ptrstd::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;
};
除了上述标准异常类外,C++ 标准库还提供了许多其他异常类,如 std::domain_error、std::invalid_argument、std::length_error 等,它们都派生自 std::runtime_error 或 std::logic_error。
以下是一个使用 C++ 标准异常类的示例:
#include <iostream>
#include <stdexcept>
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;
}