# try-catch-finally

URL: https://caijiao.org/cpp/project/try-catch
Source: docs/cpp/project/try-catch.md
Description: 本节介绍 C++ 中的异常处理机制，涵盖 'try-catch-finally' 的基本使用方法及其作用，帮助开发者安全地处理程序中的错误。

C++ 的异常处理机制通过 `try`、`catch` 和 `throw` 关键字来捕捉和处理运行时错误。尽管 C++ 中并没有内建 `finally` 语句，但可以通过一些技巧模拟类似行为。在本节中，我们将学习如何使用 `try-catch` 进行异常处理，并探索如何模拟 `finally` 的功能。

## 异常处理流程

异常处理分为三个步骤：

1. **`try` 块**：包含可能抛出异常的代码。
2. **`catch` 块**：捕获并处理异常。
3. **`throw` 语句**：用于抛出异常。

### 基本用法

```cpp
#include <iostream>
#include <stdexcept>

int divide(int a, int b) {
    if (b == 0) {
        throw std::invalid_argument("Division by zero is not allowed.");
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);  // 可能抛出异常
        std::cout << "Result: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}
````

在这个示例中，`divide()` 函数会抛出一个 `std::invalid_argument` 异常。当除数为零时，`catch` 块捕获并处理了这个异常。

## 模拟 `finally` 语句

虽然 C++ 中没有原生的 `finally` 语句，但可以使用资源管理类（如 RAII）或者 `try-catch` 配合析构函数来模拟 `finally` 的功能。

### 使用 RAII 模拟 `finally`

```cpp
#include <iostream>

class Resource {
public:
    Resource() {
        std::cout << "Resource acquired!" << std::endl;
    }

    ~Resource() {
        std::cout << "Resource released!" << std::endl;
    }
};

void functionWithException() {
    Resource res;
    throw std::runtime_error("Something went wrong!");
}

int main() {
    try {
        functionWithException();  // 可能抛出异常
    } catch (const std::runtime_error& e) {
        std::cerr << "Caught exception: " << e.what() << std::endl;
    }

    return 0;
}
```

在此示例中，`Resource` 类的析构函数将在 `try` 块抛出异常后自动调用，从而模拟 `finally` 语句的资源释放行为。

## 总结

* **`try`**：用于包装可能抛出异常的代码。
* **`catch`**：用于捕获并处理特定的异常类型。
* C++ 并不支持 `finally`，但通过 RAII 或自定义资源管理机制，能够有效模拟其功能。
