在C++中,异常处理是一种用于处理程序运行时错误的机制。它允许程序在遇到错误时优雅地恢复,而不是崩溃。C++异常处理主要依赖于三个关键字:try、catch和throw。
throw关键字抛出一个异常对象。try块之后的代码中使用catch块来捕获并处理异常。catch块中编写处理异常的代码。#include <iostream>
#include <stdexcept>
int main() {
try {
// 可能抛出异常的代码
int result = 10 / 0; // 这里会抛出一个std::runtime_error异常
} catch (const std::runtime_error& e) {
// 捕获并处理std::runtime_error异常
std::cerr << "捕获到std::runtime_error异常: " << e.what() << std::endl;
} catch (const std::exception& e) {
// 捕获并处理其他std::exception派生类的异常
std::cerr << "捕获到std::exception异常: " << e.what() << std::endl;
} catch (...) {
// 捕获所有其他类型的异常
std::cerr << "捕获到未知异常" << std::endl;
}
return 0;
}
C++标准库定义了一些常用的异常类,它们都继承自std::exception类。以下是一些常见的异常类型:
std::runtime_error:运行时错误,例如除以零。std::logic_error:逻辑错误,例如无效的参数。std::invalid_argument:无效的参数。std::out_of_range:超出范围。std::length_error:长度错误。std::bad_alloc:内存分配失败。通过合理使用C++的异常处理机制,可以提高程序的健壮性和可维护性。