(文章7) 04章-C++异常处理(下)

4.7 用类对象传递异常(进阶)

用自定义类对象传递异常,可封装更多异常信息(如错误码、描述、文件路径),还支持继承(统一处理多类型异常)。

4.7.1 自定义异常类的设计

为什么用类对象而不是基本类型? throw 0 只能传递一个数字,调用者不知道错误详情。用类对象可以把错误码、错误描述、文件路径等信息打包在一起。而且,利用继承可以让不同类型异常共享基类接口,实现统一处理。

cpp 复制代码
/*************************************************************************
  > File Name:    demo04.cpp
  > Author:       冯鹏飞
  > Description:  用类对象传递异常
  > Created Time: 2026-11-02 16:15:15
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>

using namespace std;

// 异常基类(可被继承)
class BaseException
{
protected:
    int errorCode;     // 错误码(如:1001 = 文件不存在,或者 -1 = 操作失败...)
    string errorMsg;   // 错误描述
    string extraInfo;  // 附加信息(如:文件路径,身份角色等,可以预留)
public:
    // 构造函数:初始化异常信息
    BaseException(int code, string msg, string extra = "")
        : errorCode(code), errorMsg(msg), extraInfo(extra){}

    /**
     * @brief 虚函数:获取完整错误信息(动态多态的前提)
     *        to_string() 是C++11 引入的标准库函数,位于 <string>
     */
    virtual string getError() const 
    {
        return "错误码:" + to_string(errorCode) 
                         + " | 描述:" + errorMsg 
                         + (extraInfo.empty() ? "" : " | 额外:" + extraInfo);
    }

    // 虚析构:确保子类析构正常
    virtual ~BaseException() {}
};

// 文件异常类
class FileException : public BaseException
{
public:
    FileException(int code, string msg, string filePath)
        : BaseException(code, msg, filePath) {}

    // 重写:函数名、参数列表、返回值与父类虚函数完全一致
    string getError() const override
    {
        return "[文件异常] " + BaseException::getError();
    }
};

// 数值异常类
class NumberException : public BaseException
{
public:
    NumberException(int code, string msg) : BaseException(code, msg){}

    // 重写:函数名、参数列表、返回值与父类虚函数完全一致
    string getError() const override
    {
        return "[数值异常] " + BaseException::getError();
    }
};

int main(int argc,char *argv[])
{
    
    return 0;
}

4.7.2 继承异常类的捕获原则

警示:派生类异常必须先于基类捕获!

基类 catch 会"垄断"所有派生类异常(基类指针/引用可接收派生类对象),若基类 catch 在前,派生类 catch 永远不会执行。
为什么? catch 块的匹配是顺序执行的。catch (BaseException& e) 可以接收所有 BaseException 及其派生类的异常------就像一张大网,把所有鱼(包括小鱼)都捞走了。后面的 catch (FileException& e) 永远等不到鱼。所以必须把小网(派生类)放在前面,大网(基类)放在后面兜底。

错误示例(基类 catch 在前)
cpp 复制代码
 try
    {
        string filePath = "test.txt";
        ifstream ifs(filePath, ios::in);

        if (!ifs.is_open())
        {
            throw FileException(1001, "文件不存在!", filePath);
        }

    }
    catch (BaseException& e) // 基类 catch 在前,派生类 catch不再执行
    {
        cout << e.getError() << endl;
    }
    catch (FileException& e) // 永远不执行 - 编译器可能警告 ""
    {
        cout << e.getError() << endl;
    }
    
正确示例(派生类 catch 在前)
cpp 复制代码
try
    {
        string filePath = "test.txt";
        ifstream ifs(filePath, ios::in);

        if (!ifs.is_open())
        {
            throw FileException(1001, "文件不存在!", filePath);
        }

    }
    catch (FileException& e) // 派生类先捕获
    {
        cout << e.getError() << endl;
    }
    catch (BaseException& e) // 基类后捕获(兜底)
    {
        cout << e.getError() << endl;
    }

    try
    {
        int a = 10, b = 0;
        if (b == 0) throw NumberException(1002, "除数不能为0!");
    }
    catch (NumberException &e)
    {
        cout << e.getError() << endl;
    }
    catch (BaseException& e) // 基类后捕获(兜底)
    {
        cout << e.getError() << endl;
    }
    catch (...)
    {
        cout << "其他未知错误!" << endl;
    }

运行效果:

text 复制代码
[文件异常] 错误码:1001 | 描述:文件不存在! | 额外:test.txt
[数值异常] 错误码:1002 | 描述:除数不能为 0!

**正确顺序:**派生类 catch → 基类 catch → catch(...)


4.8 标准异常(C++ 库提供)

C++ 标准库定义了一系列现成的异常类,均继承自 std::exception 类(头文件 <exception>),无需自定义即可直接使用。

4.8.1 标准异常的继承体系

logic_error vs runtime_error :logic_error 是理论上可以在编码阶段预防的错误(如参数校验),runtime_error 是运行时环境导致的、编码阶段无法预知的错误(如内存不足、文件被删除)。

4.8.2 常用标准异常说明

异常类 头文件 触发场景 核心接口
bad_alloc <new> new 分配内存失败 what():返回错误描述
out_of_range <stdexcept> vector::at(i) 越界 what():返回错误描述
invalid_argument <stdexcept> 传递无效参数(如 stoi("abc")) what():返回错误描述

4.8.3 标准异常示例

示例 1:处理 bad_alloc(内存分配失败)
cpp 复制代码
/*************************************************************************
  > File Name:    demo05.cpp
  > Author:       冯鹏飞
  > Description:  标准异常
  > Created Time: 2026-11-02 16:46:21
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <new>    // std::bad_alloc

using namespace std;

void test_bad_alloc()
{
    try
    {
        char *p = new char[0x7ffffffffffffff];  // 设计一个极大范围,保证然堆内存分失败
        delete[] p;
    }
    catch(const bad_alloc& e)  // 都不需要自己 throw
    {
        cerr << "内存分配失败:" << e.what() << endl;  // 输出:内存分配失败:std::bad_alloc
    }
    
}

int main(int argc,char *argv[])
{
    test_bad_alloc();

    return 0;
}

运行效果:

text 复制代码
内存分配失败:std::bad_alloc
示例 2:处理 out_of_range(手动检测并抛出)
cpp 复制代码
/*************************************************************************
  > File Name:    demo05.cpp
  > Author:       冯鹏飞
  > Description:  标准异常
  > Created Time: 2026-11-02 16:46:21
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <new>    // std::bad_alloc

using namespace std;

void test_out_of_range()
{
    int arr[] = {11, 22, 33}; // 最大下标:2

    try
    {
        int index = 3;
        int size = sizeof(arr) / sizeof(arr[0]);

        if (index >= size)
        {
            // 手动检测越界并抛出标准异常
            throw out_of_range("数组越界了");
        }

    }
    catch(const out_of_range& e)
    {
        cerr << "数组越界:" << e.what() << endl;
    }
    
}

int main(int argc,char *argv[])
{
    test_out_of_range();

    return 0;
}

运行结果:

text 复制代码
数组越界:数组越界了

补充 :使用 std::vector::at() 会在越界时自动 抛出 std::out_of_range,无需手动检测:

cpp 复制代码
vector<int> vec = {11, 22, 33};
try { cout << vec.at(3) << endl; }
catch (const out_of_range& e) { cerr << e.what() << endl; }
// 输出:vector::_M_range_check: __n (which is 3) >= this->size() (which is 3)
示例 3:自定义异常类继承 std::exception
cpp 复制代码
/*************************************************************************
  > File Name:    demo06.cpp
  > Author:       冯鹏飞
  > Description:  
  > Created Time: 2026-11-02 16:57:32
 ************************************************************************/

#include <iostream>
#include <string>
#include <iomanip>
#include <new>        // std::bad_alloc
#include <exception>  // std::exception

using namespace std;

// 自定义异常类
class BaseException : public exception
{
private:
    string msg;
public:
    BaseException(string msg) : msg(msg) {}

    // 重写 exception的what函数
    const char* what() const noexcept override
    {
        return msg.c_str();  // 返回c风格字符串
    }
};

int main(int argc,char *argv[])
{
    try
    {
        throw BaseException("自定义异常触发");
    }
    catch (const BaseException& e)
    {
        cerr << "捕获自定义异常:" << e.what() << endl;
    }
    catch (const exception& e) // 基类兜底
    {
        cerr << "捕获标准异常:" << e.what() << endl;
    }
    
    return 0;
}

运行效果:

text 复制代码
捕获自定义异常:自定义异常触发

建议 :实际开发中自定义异常类应优先继承 std::exception(或其子类),而不是从头写起。好处:①能被 catch (const exception& e) 统一捕获;②what() 接口与标准库一致;③可以利用 logic_error/runtime_error 的语义分类。


4.9 综合案例:文件读取的完整异常处理

整合上述知识点,实现"文件读取 + 多场景异常处理",覆盖 try-catch 嵌套、标准异常、自定义异常。

4.9.1 案例需求

  1. 读取用户指定的文件,输出内容
  2. 处理异常:文件不存在、权限不足、读取空文件、内存分配失败
  3. 用自定义异常和标准异常结合处理

4.9.2 案例代码

cpp 复制代码
/********************************************************
  > File Name:    demo08.cpp
  > Author:       fpf
  > Description:  综合案例:文件读取的完整异常处理
  > Created Time: 
 ********************************************************/
#include <iostream>
#include <string>
#include <fstream>
#include <new>        // std::bad_alloc
#include <stdexcept>  // std::out_of_range 等
#include <exception>  // std::exception

using namespace std;

// 1. 自定义文件异常类(继承标准异常基类)
class FileReadException : public exception
{
private:
    string errorInfo;
public:
    FileReadException(string filePath, string reason)
    {
        errorInfo = "[文件读取异常] 路径:" + filePath + " | 原因:" + reason;
    }

    // 重写 std::exception::what()
    const char* what() const noexcept override
    {
        return errorInfo.c_str();  // c_str() 将 C++ string 转换为 C 语言 const char*
    }
};

// 2. 文件读取函数(可能抛自定义或标准异常)
void readFileContent(const string& filePath)
{
    // 尝试在堆上分配 string(可能抛 std::bad_alloc)
    string* content = new string;

    try
    {
        // 打开文件(可能抛自定义异常)
        ifstream file(filePath);
        if (!file.is_open())
        {
            throw FileReadException(filePath, "文件不存在或权限不足");
        }

        // 逐行读取文件内容
        string line;
        while (getline(file, line))
        {
            *content += line + "\n";
        }

        // 检查是否为空文件
        if (content->empty())
        {
            throw FileReadException(filePath, "文件为空,无内容可读取");
        }

        // 输出内容
        cout << "===== 文件内容开始 =====" << endl;
        cout << *content;
        cout << "===== 文件内容结束 =====" << endl;

        // ifstream 析构时自动关闭文件,此处显式关闭也可
        file.close();
        // 释放堆内存
        delete content;
    }
    catch (...)  // 内层兜底:无论如何都要释放堆内存,避免内存泄漏
    {
        delete content;  // 确保释放
        throw;           // 异常上浮给外层处理
    }
}


// 3. 主函数:由于 readFileContent 内层 catch 执行 throw,异常上浮到 main 处理
int main(int argc, char **argv)
{
    try
    {
        string filePath;
        cout << "请输入要读取的文件路径(如:test.txt):";
        cin >> filePath;

        readFileContent(filePath);
    }
    // 捕获自定义文件异常(先捕获更具体的类型)
    catch (const FileReadException& e)
    {
        cerr << "错误:" << e.what() << endl;
    }
    // 捕获标准异常 --- 内存分配失败
    catch (const std::bad_alloc& e)  // 明确 std:: 前缀,即使有 using namespace std
    {
        cerr << "错误:内存分配失败!" << e.what() << endl;
    }
    // 捕获其他标准异常(如 out_of_range 等,作为兜底)
    catch (const exception& e)
    {
        cerr << "错误:" << e.what() << endl;
    }
    // 万能捕获(兜底未知异常)
    catch (...)
    {
        cerr << "错误:未知异常,请检查程序!" << endl;
    }

    cout << "\n程序正常结束!" << endl;
    return 0;
}

4.9.3 运行结果(文件不存在)

text 复制代码
请输入要读取的文件路径(如 test.txt):nonexist.txt
错误:[文件读取异常] 路径:nonexist.txt | 原因:文件不存在或权限不足

程序正常结束!

4.9.4 运行效果(空文件)

text 复制代码
请输入要读取的文件路径(如 test.txt):empty.txt
错误:[文件读取异常] 路径:empty.txt | 原因:文件为空,无内容可读取

程序正常结束!

本案例的关键技巧:

  • 内层 catch(...) + throw; 模式:内层只负责释放资源(delete content),然后重新抛出,让外层的具体 catch 块做业务处理
  • catch 顺序:最具体(FileReadException)→ 标准异常(bad_alloc)→ 基类兜底(exception)→ 万能兜底(...)
  • bad_alloc 单独放前面:虽然它也是 exception 的派生类,但我们想对它做特殊处理(提示"内存不足"),所以单独放前面

4.10 异常处理核心总结

  1. 核心原则:异常抛出与处理分离,抛出模块只传信息,处理模块专注解决。
  2. catch 顺序 :派生类异常 catch 在前,基类在后;万能 catch(...) 在最后。
  3. 资源安全 :析构函数不抛异常(C++11 起默认 noexcept);嵌套 try 中用内层 catch(...) + throw; 确保资源释放(RAII 更推荐)。
  4. 标准异常优先 :优先使用标准库异常(如 std::bad_alloc、std::out_of_range),减少自定义成本;自定义异常应继承 std::exception。
  5. 未捕获风险 :始终确保异常有对应的 catch,避免未捕获导致 std::terminate() 终止程序。
  6. noexcept 关键字 :C++11 起推荐使用 noexcept 声明不抛异常的函数;移动构造/析构函数应尽可能标记 noexcept 以利于 STL 容器优化。

下一章预告 :第5章将学习泛型编程(模板)------用一种"模具"(模板)处理多种数据类型,告别为 int/double/char 各写一套相同逻辑代码的低效时代。模板是 STL 的基础,也是 C++ 区别于 C 语言的重要特性之一。

相关推荐
cpolar技术支持22 分钟前
rsync 只看「大小 + 修改时间」:源文件改成 `CCCC-v3`、目标还是 `DDDD-v4`,三条同步命令 rc 全是 0
linux·rsync·cpolar·nas·数据同步
LabVIEW开发11 小时前
ALMEMO 采集器 + LabVIEW 多路温度怎么采?
网络·labview
yyzc1111111 小时前
当中小微实体店面临经营困境时如何借助顺成汇创旗下荟生意品牌实现数字化智慧营销
大数据·运维·人工智能
Rsingstarzengjx14 小时前
第三十九章 Linux PWM 驱动实验
linux·运维·服务器
SeanQhl15 小时前
BoostKit 环境准备
linux·openeuler·鲲鹏·boostkit·软件源
笔记本note16 小时前
Linux 内存管理
linux·服务器·内存管理
郝学胜-神的一滴16 小时前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
GeW18 小时前
入行 Linux 与数据库运维:一条路径、三项习惯、一个考证观
linux·数据库
王亚博_Abel18 小时前
域名是怎么变成 IP 的?手拆 DNS 解析四个实验实测
网络·网络协议·tcp/ip