文章

C++ 异常处理

C++ 异常处理

C++主要有以下三种异常处理的关键字

  • throw: 当问题出现时,程序通过throw抛出一个异常。
  • catch: 使用catch来捕获异常
  • try: try块中的代码标识将被激活的特定异常。它后面通常跟着一个或多个 catch 块。

基本语法

1
2
3
4
5
6
7
8
9
try {
    // 可能会出错的代码
    if (条件不满足) {
        throw 错误对象;   // 抛出异常
    }
} 
catch (类型 参数) {
    // 处理异常
}

简单示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;

int main() {
    try {
        int a, b;
        cout << "Enter two numbers: ";
        cin >> a >> b;

        if (b == 0) {
            throw runtime_error("除数不能为 0");
        }

        cout << "Result: " << (a / b) << endl;
    } 
    catch (const runtime_error& e) {
        cout << "捕获异常: " << e.what() << endl;
    }

    return 0;
}

自定义异常类

C++允许使用std::exception来定义自己的异常类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <exception>
using namespace std;

class MyException : public exception {
public:
    const char* what() const noexcept override {
        return "自定义异常: 出错了!";
    }
};

int main() {
    try {
        throw MyException();
    } 
    catch (const exception& e) {
        cout << e.what() << endl;
    }
}

常见标准异常

异常描述
std::runtime_error理论上不可以通过读取代码来检测到的异常。
std::logic_error理论上可以通过读取代码来检测到的异常。
std::out_of_range该异常可以通过方法抛出,例如 std::vectorstd::bitset<>::operator[]()
std::invalid_argument当使用了无效的参数时,会抛出该异常。
std::exception该异常是所有标准 C++ 异常的父类。
std::bad_alloc该异常可以通过 new 抛出。
std::bad_cast该异常可以通过 dynamic_cast 抛出。
std::bad_exception这在处理 C++ 程序中无法预期的异常时非常有用。
std::bad_typeid该异常可以通过 typeid 抛出。
std::domain_error当使用了一个无效的数学域时,会抛出该异常。
std::length_error当创建了太长的 std::string 时,会抛出该异常。
std::overflow_error当发生数学上溢时,会抛出该异常。
std::range_error当尝试存储超出范围的值时,会抛出该异常。
std::underflow_error当发生数学下溢时,会抛出该异常。
本文由作者按照 CC BY 4.0 进行授权