C++ try catch异常处理_C++ exception用法详解

C++中异常处理通过try、catch和throw实现,throw抛出异常,try捕获可能出错代码,catch处理对应异常,提升程序健壮性。

在C++中,异常处理是一种用于应对程序运行时错误的机制。通过 trycatchthrow 关键字,开发者可以优雅地处理错误情况,避免程序崩溃,提高代码的健壮性。下面详细介绍C++中异常处理的基本用法和常见实践。

基本语法结构

C++的异常处理由三部分组成:

  • throw:当检测到错误时,使用 throw 抛出一个异常对象或值。
  • try:将可能出错的代码包裹在 try 块中。
  • catch:紧跟在 try 后面,用于捕获并处理异常。

try {
    // 可能抛出异常的代码
    if (error) {
        throw "Something went wrong";
    }
}
catch (const char* msg) {
    // 处理字符串类型的异常
    std::cout << "Error: " << msg << std::endl;
}

捕获不同类型的异常

catch 块可以根据抛出的异常类型进行匹配。C++支持捕获多种类型,包括内置类型、类对象等。

try {
    throw 42;                    // 抛出 int
    // throw std::runtime_error("File not found");  // 或抛出标准异常
}
catch (int e) {
    std::cout << "Caught int: " << e << std::endl;
}
catch (const std::exception& e) {
    std::cout << "Caught standard exception: " << e.what() << std::endl;
}
catch (...) {
    std::cout << "Caught unknown exception" << std::endl;
}

注意:catch 的匹配顺序很重要,应将更具体的异常类型放在前面,避免被泛化的 catch(...) 拦截。

使用标准异常类

C++标准库定义了丰富的异常类,位于 头文件中,推荐在实际开发中使用这些标准异常,而不是原始类型。

  • std::invalid_argument:参数非法。
  • std::out_of_range:访问越界。
  • std::runtime_error:运行时错误。
  • std::logic_error:逻辑错误。

#include 
#include 

double divide(int a, int b) { if (b == 0) { throw std::invalid_argument("Division by zero is not allowed."); } return static_cast(a) / b; }

int main() { try { double result = divide(10, 0); } catch (const std::invalid_argument& e) { std::cout << "Error: " << e.what() << std::endl; } return 0; }

异常安全与资源管理

使用异常时需注意资源泄漏问题。推荐结合RAII(Resource Acquisition Is Initialization)技术,利用对象的构造和析构自动管理资源。

例如,使用 std::unique_ptrstd::vector 可以确保即使抛出异常,内存也能被正确释放。

void risky_function() {
    std::unique_ptr data(new int[1000]);
if (/* some error */) {
    throw std::runtime_error("Oops");
}
// 即使抛出异常,data 也会自动释放

}

基本上就这些。掌握 try-catch 机制有助于写出更稳定、易维护的C++程序。关键是合理抛出异常、精准捕获,并配合RAII保障资源安全。