cpp_exception - ShenYj/ShenYj.github.io GitHub Wiki

异常捕获

  • 异常是一种在程序运行过程中可能会发生的错误(比如内存不够)
  • 异常没有被处理,会导致程序终止
  • throw异常后,会在当前函数中查找匹配的catch,找不到就 终止当前函数代码,去上一层函数中查找。如果最终都找不 到匹配的catch,整个程序就会终止

捕获异常

try {
    /// 可能会抛出异常的代码
} catch (...) { /// ...表示所有类型的异常
    
}

catch 允许多个

try {
    /// 可能会抛出异常的代码
} catch (异常类型 [变量名]) {
    /// 异常处理代码
} catch (异常类型 [变量名]) {
    /// 异常处理代码
} ...
for (int i = 0; i < 9999; i++) {
    try {
        int *p = new int[999999];
    } catch (...) {
        cout << "内存不够用" << endl;
        break;
    }
}

抛出异常

int divide(int v1, int v2) {
    if (v2 == 0) throw "不能除以0";
    return v1 / v2;
}

try {
    int a = 10;
    int b = 0;
    cout << divide(a, b) << endl;
} catch (string exception) { /// 如果写成int exception,就不能捕获到异常,因为抛出异常的类型和捕获的异常类型不同,无法被捕获
    cout << string << endl;
}

为了增强可读性和方便团队协作,如果函数内部可能会抛出异常,建议函数声明一下异常类型

/// 抛出任意可能的异常
void func1() { }

/// 不抛出任何异常
void func2() throw() { }

/// 只抛出 int、double类型的异常
void func3() throw(int, double) { }

自定义异常类型

class Exception {
public:
    virtual string what() const = 0;
};

class DivideException: public Exception {
public:
    string what() const { return "不能除以0" }
};

int divide(int v1, int v2) throw(Exception) {
    if (v2 == 0) throw DivideException();
    return v1 / v2;
}
try {
    int a = 10;
    int b = 0;
    int c = divide(a, b);
} catch (const Exception &exception) {
    cout << exception.what() << endl;
}

根据实际情况决定使用 const 或 非const 去封装定义

标准异常 std

. .

try {
    int size = 999999;
    for (size_t i = 0; i < size; i++) {
        int *p = new int[size];
    }
} catch (std::bad_alloc exception) {
    cout << exception.what() << endl;
}
⚠️ **GitHub.com Fallback** ⚠️