返回首页 C++ 模板

异常处理模板

try-catch 捕获运行时错误——让程序更健壮

异常处理 try-catch throw GESP4
#include <bits/stdc++.h>
using namespace std;

int divide(int a, int b) {
    if (b == 0) throw runtime_error("除零错误");
    return a / b;
}

int main() {
    // 基本 try-catch
    try {
        int result = divide(10, 0);
        cout << result << endl;
    } catch (const runtime_error &e) {
        cerr << "捕获异常: " << e.what() << endl;
    }

    // 多种异常类型
    try {
        int arr[5] = {1,2,3,4,5};
        int idx;
        cin >> idx;
        if (idx < 0 || idx >= 5) throw out_of_range("数组越界");
        cout << arr[idx] << endl;
    } catch (const out_of_range &e) {
        cerr << e.what() << endl;
    } catch (...) {
        cerr << "未知异常" << endl;
    }

    return 0;
}

📖 要点说明

⚠️ 常见错误