C++ 从入门到精通C++ 从入门到精通
首页
基础教程
进阶教程
实战项目
编程指南
首页
基础教程
进阶教程
实战项目
编程指南
  • 💪 进阶基础

    • 📚 C++ 进阶教程
    • 第8章 - 指针基础
    • 第9章 - 引用和动态内存
    • 第10章 - 结构体和枚举
    • 第11章 - 文件操作
    • 第12章 - 预处理器和命名空间
  • 🎯 面向对象编程

    • 第13章 - 类和对象基础
    • 第14章 - 构造函数和析构函数
    • 第15章 - 封装、继承、多态
    • 第16章 - 运算符重载
    • 第17章 - 模板基础
    • 第18章 - 异常处理
  • 📦 STL 标准模板库

    • 第19章 - Vector 和 String
    • 第20章 - 容器类
    • 第21章 - Map 和 Set
    • 第22章 - 算法和迭代器

第18章 - 异常处理

嗨,朋友!我是长安。

异常处理用于处理程序运行时的错误,让程序更健壮。

⚠️ try-catch基础

#include <iostream>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw "除数不能为0!";  // 抛出异常
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        cout << "结果:" << result << endl;
    } catch (const char* msg) {
        cout << "错误:" << msg << endl;
    }
    
    cout << "程序继续运行..." << endl;
    return 0;
}

🎯 自定义异常类

class DivideByZeroException {
private:
    string message;
public:
    DivideByZeroException(string msg) : message(msg) {}
    string what() { return message; }
};

int safeDivide(int a, int b) {
    if (b == 0) {
        throw DivideByZeroException("除数为零!");
    }
    return a / b;
}

int main() {
    try {
        int result = safeDivide(10, 0);
    } catch (DivideByZeroException& e) {
        cout << "异常:" << e.what() << endl;
    }
}

➡️ 第19章 - Vector 和 String

最近更新: 2025/12/26 17:25
Contributors: 王长安
Prev
第17章 - 模板基础