> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/complexity-debug/exceptions.md).

# 异常处理

### 什么是异常

程序运行中出现的非正常情况（如除以 0、数组越界、内存不足）称为异常。异常处理让程序在出错时不直接崩溃，而是跳转到处理代码。

### try-catch 结构

```cpp
#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        int a = 10, b = 0;
        if (b == 0) throw runtime_error("除数不能为 0");
        cout << a / b;
    } catch (const runtime_error &e) {
        cout << "捕获异常：" << e.what() << endl;
    } catch (...) {          // 捕获任意类型异常
        cout << "未知异常" << endl;
    }
    cout << "程序继续运行" << endl;
    return 0;
}
```

### 关键字

* `try`：包裹可能出错的代码
* `throw`：抛出异常
* `catch`：捕获并处理异常

### 常见异常类型（）

`runtime_error`、`logic_error`、`out_of_range`、`invalid_argument` 等。

### 使用建议

* 异常处理有性能开销，竞赛中一般用于简单场景。
* 更常见的是用条件判断（如提前 return）来避免错误。
* catch 按从具体到一般的顺序书写。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/complexity-debug/exceptions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
