阅读量:4
C++ 标准异常类主要包括 std::exception 和其派生类
- std::exception:这是 C++ 标准库中所有异常类的基类。它提供了一个名为 what() 的虚函数,用于返回异常的描述信息。通常,我们可以通过捕获
std::exception类型的异常来处理所有标准异常。
#include
#include
int main() {
try {
throw std::runtime_error("An error occurred");
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
- std::runtime_error:这是一个派生自
std::exception的异常类,用于表示运行时错误。它接受一个字符串参数作为异常的描述信息。
#include
#include
int main() {
try {
throw std::runtime_error("An error occurred");
} catch (const std::runtime_error& e) {
std::cerr << "Caught runtime_error: " << e.what() << std::endl;
}
return 0;
}
- std::out_of_range:这是一个派生自
std::runtime_error的异常类,用于表示访问数组或其他容器时越界的情况。
#include
#include
#include
int main() {
std::vector<int> vec = {1, 2, 3};
try {
std::cout << vec[3] << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "Caught out_of_range: " << e.what() << std::endl;
}
return 0;
}
要创建自定义异常类,只需从 std::exception 或其他标准异常类派生一个新的类,并实现 what() 函数。例如:
#include
#include
class MyCustomException : public std::exception {
public:
const char* what() const noexcept override {
return "My custom exception occurred";
}
};
int main() {
try {
throw MyCustomException();
} catch (const MyCustomException& e) {
std::cerr << "Caught custom exception: " << e.what() << std::endl;
}
return 0;
}
在这个例子中,我们创建了一个名为 MyCustomException 的自定义异常类,它继承自 std::exception 并重写了 what() 函数。在主函数中,我们抛出了一个 MyCustomException 类型的异常,并在 catch 块中捕获并处理它。
以上就是关于“C++标准异常类与自定义异常”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm