Skip to content

L4_08 异常处理

一、异常处理机制

1.1 概念

异常处理是一种处理程序运行时错误的机制。

1.2 异常处理的组成

  • try:可能抛出异常的代码块
  • catch:捕获并处理异常
  • throw:抛出异常

1.3 基本语法

cpp
try {
    // 可能抛出异常的代码
    if (error_condition) {
        throw exception;
    }
} catch (exception_type e) {
    // 处理异常
}

二、常用方法

2.1 抛出异常

cpp
#include <iostream>
using namespace std;

double divide(int numerator, int denominator) {
    if (denominator == 0) {
        throw "除零错误";
    }
    return (double)numerator / denominator;
}

int main() {
    try {
        double result = divide(10, 0);
        cout << "结果: " << result << endl;
    } catch (const char* msg) {
        cout << "异常: " << msg << endl;
    }
    return 0;
}

2.2 捕获不同类型的异常

cpp
#include <iostream>
using namespace std;

void process(int value) {
    if (value < 0) {
        throw -1;
    } else if (value == 0) {
        throw string("值为零");
    }
}

int main() {
    try {
        process(-5);
    } catch (int err) {
        cout << "整数异常: " << err << endl;
    } catch (string msg) {
        cout << "字符串异常: " << msg << endl;
    }
    return 0;
}

2.3 标准异常类

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

int main() {
    try {
        int* arr = new int[1000000000000ULL];
    } catch (bad_alloc& e) {
        cout << "内存分配失败: " << e.what() << endl;
    }
    
    try {
        int arr[5] = {1, 2, 3, 4, 5};
        cout << arr[10];  // 越界访问
    } catch (out_of_range& e) {
        cout << "数组越界: " << e.what() << endl;
    }
    
    return 0;
}

三、自定义异常

3.1 创建自定义异常类

cpp
#include <iostream>
#include <exception>
#include <string>
using namespace std;

class MyException : public exception {
private:
    string message;
public:
    MyException(const string& msg) : message(msg) {}
    
    const char* what() const noexcept override {
        return message.c_str();
    }
};

void doSomething(int value) {
    if (value < 0) {
        throw MyException("值不能为负数");
    }
}

int main() {
    try {
        doSomething(-1);
    } catch (MyException& e) {
        cout << "自定义异常: " << e.what() << endl;
    }
    return 0;
}

四、异常处理的最佳实践

4.1 异常规格说明(不推荐)

cpp
void func() throw(int, string);  // 可能抛出int或string异常
void func() throw();             // 不抛出任何异常(已废弃)

4.2 noexcept 关键字(C++11)

cpp
void func() noexcept {
    // 不抛出异常的函数
}

4.3 RAII 原则

cpp
#include <fstream>
using namespace std;

void processFile() {
    ifstream file("data.txt");  // 自动析构时关闭文件
    
    // 处理文件
}  // 文件自动关闭,即使发生异常

五、示例程序

cpp
#include <iostream>
#include <exception>
#include <string>
using namespace std;

class NegativeException : public exception {
public:
    const char* what() const noexcept override {
        return "数值不能为负数";
    }
};

class ZeroException : public exception {
public:
    const char* what() const noexcept override {
        return "数值不能为零";
    }
};

int calculate(int a, int b) {
    if (a < 0 || b < 0) {
        throw NegativeException();
    }
    if (b == 0) {
        throw ZeroException();
    }
    return a / b;
}

int main() {
    try {
        int result = calculate(10, -2);
        cout << "结果: " << result << endl;
    } catch (NegativeException& e) {
        cout << "捕获异常: " << e.what() << endl;
    } catch (ZeroException& e) {
        cout << "捕获异常: " << e.what() << endl;
    } catch (...) {
        cout << "未知异常" << endl;
    }
    
    return 0;
}

百炼成钢,融会贯通