阅读时间:约15分钟 | 📊 难度:中级 | 🎯 目标读者:C++开发者、面试准备

📋 目录

⚡ 1. C语言传统错误处理方式

⚠️ 终止程序(Assert):如assert,缺陷:用户难以接受。如发生内存错误,除0错误时就会终止程序。
🔢 返回错误码:缺陷:需要程序员自己去查找对应的错误。如系统的很多库的接口函数都是通过把错误码放到errno中,表示错误。
实际中C语言基本都是使用返回错误码的方式处理错误,部分情况下使用终止程序处理非常严重的错误。

🚀 2. C++异常概念

异常是一种处理错误的方式,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接的调用者处理这个错误。

🔑 2.1 核心关键字

  • throw: 当问题出现时,程序会抛出一个异常。这是通过使用 throw 关键字来完成的。
  • catch: 在您想要处理问题的地方,通过异常处理程序捕获异常.catch 关键字用于捕获异常,可以有多个catch进行捕获。
  • try: try 块中的代码标识将被激活的特定异常,它后面通常跟着一个或多个 catch 块。

如果有一个块抛出一个异常,捕获异常的方法会使用 try 和 catch 关键字。try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码。使用 try/catch 语句的语法如下所示:

📝 2.2 基本语法结构:

try
{
  // 保护的标识代码
}catch( ExceptionName e1 )
{
  // catch 块
}catch( ExceptionName e2 )
{
  // catch 块
}catch( ExceptionName eN )
{
  // catch 块
}

🔧 3. 异常的使用

🔥3.1 异常的抛出和捕获

异常的抛出和匹配原则
  • 异常是通过抛出对象而引发的,该对象的类型决定了应该激活哪个catch的处理代码。
  • 选中的处理代码是调用链中与该对象类型匹配且离抛出异常位置最近的那一个。
  • 抛出异常对象后,会生成一个异常对象的拷贝,因为抛出的异常对象可能是一个临时对象,所以会生成一个拷贝对象,这个拷贝的临时对象会在被catch以后销毁。(这里的处理类似于函数的传值返回)。
  • catch(…)可以捕获任意类型的异常,问题是不知道异常错误是什么。
  • 实际中抛出和捕获的匹配原则有个例外,并不都是类型完全匹配,可以抛出的派生类对象,使用基类捕获,这个在实际中非常实用。
在函数调用链中异常栈展开匹配原则
  • 首先检查throw本身是否在try块内部,如果是再查找匹配的catch语句。如果有匹配的,则调到catch的地方进行处理。
  • 没有匹配的catch则退出当前函数栈,继续在调用函数的栈中进行查找匹配的catch。
  • 如果到达main函数的栈,依旧没有匹配的,则终止程序。上述这个沿着调用链查找匹配的catch子句的过程称为栈展开。所以实际中我们最后都要加一个catch(…)捕获任意类型的异常,否则当有异常没捕获,程序就会直接终止。
  • 找到匹配的catch子句并处理以后,会继续沿着catch子句后面继续执行。
    在这里插入图片描述
double Division(int a, int b)
{
     // 当b == 0时抛出异常
	 if (b == 0)
	   throw "Division by zero condition!";
	    else
	        return ((double)a / (double)b);
}
void Func()
{
	 int len, time;
	 cin >> len >> time;
	 cout << Division(len, time) << endl;
}
int main()
{
	try {
		 Func();
	}catch (const char* errmsg){
		 cout << errmsg << endl;
	}catch(...){
	   cout<<"unkown exception"<<endl;           
	}
	return 0;
}

🔥3.2 异常的重新抛出

有可能单个的catch不能完全处理一个异常,在进行一些校正处理以后,希望再交给更外层的调用链函数来处理,catch则可以通过重新抛出将异常传递给更上层的函数进行处理。

double Division(int a, int b)
{
	 // 当b == 0时抛出异常
	 if (b == 0)
	 {
	 throw "Division by zero condition!";
	 }
	 return (double)a / (double)b;
}
void Func()
{
	 // 这里可以看到如果发生除0错误抛出异常,另外下面的array没有得到释放。
	 // 所以这里捕获异常后并不处理异常,异常还是交给外面处理,这里捕获了再
	 // 重新抛出去。
	 int* array = new int[10];
	 try {
		 int len, time;
		 cin >> len >> time;
		 cout << Division(len, time) << endl;
	 } catch (...){
		 cout << "delete []" << array << endl;
		 delete[] array;
		 throw;
	 }
	 // ...
	 cout << "delete []" << array << endl;
	 delete[] array;
}
int main()
{
	 try{
		 Func();
	 }catch (const char* errmsg){
		 cout << errmsg << endl;
	 }
	 return 0;
}
🔥3.3 异常安全
  • 构造函数完成对象的构造和初始化,最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化。
  • ** 析构函数主要完成资源的清理,最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内存泄漏、句柄未关闭等)。**
  • C++中异常经常会导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和unlock之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题。
🔥3.4 异常规范
  1. 异常规格说明的目的是为了让函数使用者知道该函数可能抛出的异常有哪些。 可以在函数的
    后面接throw(类型),列出这个函数可能抛掷的所有异常类型。
  2. 函数的后面接throw(),表示函数不抛异常。
  3. 若无异常接口声明,则此函数可以抛掷任何类型的异常。
// 这里表示这个函数会抛出A/B/C/D中的某种类型的异常
void fun() throw(A,B,C,D);
// 这里表示这个函数只会抛出bad_alloc的异常
void* operator new (std::size_t size) throw (std::bad_alloc);
// 这里表示这个函数不会抛出异常
void* operator delete (std::size_t size, void* ptr) throw();
// C++11 中新增的noexcept,表示不会抛异常
thread() noexcept;
thread (thread&& x) noexcept;

🏗️ 4.自定义异常体系

实际使用中很多公司都会自定义自己的异常体系进行规范的异常管理,因为一个项目中如果大家随意抛异常,那么外层的调用者基本就没办法玩了,所以实际中都会定义一套继承的规范体系。这样大家抛出的都是继承的派生类对象,捕获一个基类就可以了:
在这里插入图片描述

#include <iostream>
#include <string>
#include <exception>
#include <memory>

// 🔧 基础异常类
class BaseException : public std::exception {
protected:
    std::string error_msg;
    int error_code;
    std::string timestamp;
    
public:
    BaseException(const std::string& msg, int code) 
        : error_msg(msg), error_code(code) {
        // 可以在这里记录时间戳等上下文信息
    }
    
    virtual const char* what() const noexcept override {
        return error_msg.c_str();
    }
    
    virtual std::string getFullMessage() const {
        return "错误代码: " + std::to_string(error_code) + 
               ", 消息: " + error_msg;
    }
    
    int getErrorCode() const { return error_code; }
    
    virtual ~BaseException() = default;
};

// 💾 数据库异常
class DatabaseException : public BaseException {
private:
    std::string sql_query;
    std::string database_name;
    
public:
    DatabaseException(const std::string& msg, int code, 
                     const std::string& sql, const std::string& db)
        : BaseException(msg, code), sql_query(sql), database_name(db) {}
    
    const char* what() const noexcept override {
        static std::string full_msg;
        full_msg = "数据库异常 [" + database_name + "]: " + 
                   error_msg + "\nSQL: " + sql_query;
        return full_msg.c_str();
    }
    
    std::string getSQL() const { return sql_query; }
    std::string getDatabase() const { return database_name; }
};

// 🌐 网络异常
class NetworkException : public BaseException {
private:
    std::string endpoint;
    int http_status;
    
public:
    NetworkException(const std::string& msg, int code, 
                    const std::string& ep, int status)
        : BaseException(msg, code), endpoint(ep), http_status(status) {}
    
    const char* what() const noexcept override {
        static std::string full_msg;
        full_msg = "网络异常 [" + endpoint + "]: " + 
                   error_msg + " (HTTP " + std::to_string(http_status) + ")";
        return full_msg.c_str();
    }
    
    int getHttpStatus() const { return http_status; }
};

// 📁 文件系统异常
class FileSystemException : public BaseException {
private:
    std::string file_path;
    std::string operation;
    
public:
    FileSystemException(const std::string& msg, int code, 
                       const std::string& path, const std::string& op)
        : BaseException(msg, code), file_path(path), operation(op) {}
    
    const char* what() const noexcept override {
        static std::string full_msg;
        full_msg = "文件系统异常 [" + operation + " " + file_path + "]: " + error_msg;
        return full_msg.c_str();
    }
};

// 🎯 使用示例
class DatabaseManager {
public:
    void connect() {
        // 模拟连接失败
        throw DatabaseException("连接超时", 1001, 
                              "SELECT * FROM users", "production_db");
    }
};

class FileProcessor {
public:
    void processFile(const std::string& path) {
        // 模拟文件操作失败
        throw FileSystemException("权限不足", 2001, path, "open");
    }
};

void processUserRequest() {
    try {
        DatabaseManager db;
        db.connect();
        
        FileProcessor fp;
        fp.processFile("/data/user.txt");
    } 
    catch (const DatabaseException& e) {
        std::cerr << "🔴 数据库错误: " << e.what() << std::endl;
        std::cerr << "SQL语句: " << e.getSQL() << std::endl;
    } 
    catch (const FileSystemException& e) {
        std::cerr << "🟡 文件系统错误: " << e.what() << std::endl;
    } 
    catch (const BaseException& e) {
        std::cerr << "⚫ 基础异常: " << e.getFullMessage() << std::endl;
    } 
    catch (const std::exception& e) {
        std::cerr << "⚪ 标准异常: " << e.what() << std::endl;
    } 
    catch (...) {
        std::cerr << "❓ 未知异常类型" << std::endl;
    }
}

int main() {
    processUserRequest();
    return 0;
}

📚 5.C++标准库异常体系

C++标准库提供了一套异常类体系,定义在<std::except>头文件中:
在这里插入图片描述
在这里插入图片描述
说明:实际中我们可以可以去继承exception类实现自己的异常类。但是实际中很多公司像上面一样自己定义一套异常继承体系。因为C++标准库设计的不够好用。

#include <iostream>
#include <stdexcept>
#include <vector>
#include <string>

void demonstrateStandardExceptions() {
    try {
        // 1. logic_error 系列(逻辑错误)
        std::string str = "hello";
        if (str.length() < 10) {
            throw std::out_of_range("字符串索引越界");
        }
    } 
    catch (const std::logic_error& e) {
        std::cout << "逻辑错误: " << e.what() << std::endl;
    }
    
    try {
        // 2. runtime_error 系列(运行时错误)
        std::vector<int> vec;
        vec.reserve(1000000000);  // 可能抛出bad_alloc
        vec.at(10) = 100;         // 可能抛出out_of_range
    } 
    catch (const std::bad_alloc& e) {
        std::cout << "内存分配失败: " << e.what() << std::endl;
    } 
    catch (const std::runtime_error& e) {
        std::cout << "运行时错误: " << e.what() << std::endl;
    } 
    catch (const std::exception& e) {
        std::cout << "标准异常: " << e.what() << std::endl;

🌲 6.异常的优缺点

🟢 C++异常的优点:

1. 清晰的错误信息传递
  • 异常对象定义好了,相比错误码的方式可以清晰准确的展示出错误的各种信息,甚至可以包含堆栈调用的信息,这样可以帮助更好的定位程序的bug
// 传统错误码方式
int processFile(const char* filename) {
    FILE* file = fopen(filename, "r");
    if (!file) {
        return errno;  // 只知道错误码,不知道具体原因
    }
    // ... 处理文件
    fclose(file);
    return 0;
}

// 异常方式
void processFileBetter(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("无法打开文件: " + filename + 
                               ",原因: " + strerror(errno));
    }
    // ... 处理文件
}
2. 简化错误处理流程
  • 返回错误码的传统方式有个很大的问题就是,在函数调用链中,深层的函数返回了错误,那么我们得层层返回错误,最外层才能拿到错误,具体看下面的详细解释。
int ConnnectSql()
{
	 // 用户名密码错误
	 if (...)
		 return 1;
	  
	 // 权限不足
	 if (...)
		 return 2;
}
  
int ServerStart() {
	 if (int ret = ConnnectSql() < 0)
		 return ret;
	 int fd = socket();
	 if(fd < 0return errno;
}
  
int main() {
	 if(ServerStart()<0)
	 ...
	  
	 return 0;
}

代码解释:

  1. 上面这段伪代码我们可以看到ConnnectSql中出错了,先返回给ServerStart,ServerStart再返回给main函数,main函数再针对问题处理具体的错误。
  2. 如果是异常体系,不管是ConnnectSql还是ServerStart及调用函数出错,都不用检查,因为抛出的异常会直接跳到main函数。
3. 兼容第三方库的异常机制
  • 很多优秀的第三方库(如 Boost、Google Test、Google Mock 等)都使用异常机制来报告错误。如果我们不使用异常,就无法充分利用这些库的错误处理能力,或者需要编写额外的适配层。
#include <boost/filesystem.hpp>
#include <gtest/gtest.h>

// Boost 文件系统操作会抛出异常
void copyFileWithBoost(const std::string& src, const std::string& dst) {
    try {
        boost::filesystem::copy_file(src, dst);
    } catch (const boost::filesystem::filesystem_error& e) {
        // 处理 Boost 库抛出的异常
        std::cerr << "文件复制失败: " << e.what() << std::endl;
        throw;  // 重新抛出或处理
    }
}

// Google Test 的断言失败也会抛出异常
TEST(MyTest, TestCase) {
    EXPECT_THROW({
        someFunctionThatShouldThrow();
    }, std::runtime_error);
}
4. 处理无返回值函数的错误
  • 某些函数(如构造函数、重载运算符)没有返回值,无法通过返回值传递错误码。在这些情况下,异常是处理错误的唯一合理方式。
class Vector {
private:
    int* data;
    size_t size;
    
public:
    // 构造函数无法返回错误码
    Vector(size_t n) : size(n) {
        if (n > 1000000) {
            throw std::bad_alloc();  // 内存过大,无法分配
        }
        data = new int[n];
        if (!data) {
            throw std::bad_alloc();  // 内存分配失败
        }
    }
    
    // 重载下标运算符,无法通过返回值表示错误
    int& operator[](size_t pos) {
        if (pos >= size) {
            throw std::out_of_range("Vector::operator[]: 索引 " + 
                                  std::to_string(pos) + 
                                  " 超出范围 [0, " + 
                                  std::to_string(size - 1) + "]");
        }
        return data[pos];
    }
    
    // 拷贝赋值运算符
    Vector& operator=(const Vector& other) {
        if (this != &other) {
            delete[] data;
            size = other.size;
            data = new int[size];
            if (!data) {
                throw std::bad_alloc();  // 无法返回错误码
            }
            std::copy(other.data, other.data + size, data);
        }
        return *this;
    }
    
    ~Vector() {
        delete[] data;
    }
};

// 使用示例
int main() {
    try {
        Vector v(10000000);  // 可能抛出 bad_alloc
        v[100] = 42;         // 正常访问
        v[1000] = 10;        // 可能抛出 out_of_range
        
        Vector v2 = v;       // 拷贝构造,可能抛出异常
    } catch (const std::exception& e) {
        std::cerr << "错误: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

代码解释:

  1. 构造函数:当内存分配失败时,构造函数无法返回错误码,只能通过异常通知调用者。
  2. operator[]:当索引越界时,无法通过返回值表示错误(因为返回的是引用,必须返回有效对象的引用),只能抛出异常或终止程序。
  3. operator=:拷贝赋值运算符在内存分配失败时也无法返回错误码,只能抛出异常。

这些情况下,异常提供了比终止程序(如 assertabort)更优雅的错误处理方式,允许调用者决定如何处理错误。
出错,都不用检查,因为抛出的异常会直接跳到main函

🔴 C++异常的缺点:

  1. 异常会导致程序的执行流乱跳,并且非常的混乱,并且是运行时出错抛异常就会乱跳。这会导致我们跟踪调试时以及分析程序时,比较困难。
  2. 异常会有一些性能的开销。当然在现代硬件速度很快的情况下,这个影响基本忽略不计。
  3. C++没有垃圾回收机制,资源需要自己管理。有了异常非常容易导致内存泄漏、死锁等异常安全问题。这个需要使用RAII来处理资源的管理问题。学习成本较高。
  4. C++标准库的异常体系定义得不好,导致大家各自定义各自的异常体系,非常的混乱。
  5. 异常尽量规范使用,否则后果不堪设想,随意抛异常,外层捕获的用户苦不堪言。所以异常规范有两点:一、抛出异常类型都继承自一个基类。二、函数是否抛异常、抛什么异常,都使用 func()和 throw();的方式规范化。

📊 异常使用建议

在实际开发中,应该根据具体情况选择合适的错误处理方式:

1. 适合使用异常的场景
  • 构造函数失败:构造函数无法返回错误码,异常是更好的选择
  • 操作符重载:操作符通常没有返回错误码的机制
  • 库接口设计:提供清晰的错误信息给调用者
  • 不可恢复的错误:如内存不足、文件不存在等
2. 适合使用错误码的场景
  • 性能敏感代码:如游戏引擎、高频交易系统
  • C语言接口:需要与C代码交互
  • 可预期的错误:如用户输入验证、网络连接超时
  • 嵌入式系统:资源受限环境
3. 最佳实践
// 1. 使用RAII管理资源
class FileHandle {
private:
    FILE* file;
    
public:
    FileHandle(const char* filename) : file(fopen(filename, "r")) {
        if (!file) {
            throw std::runtime_error("无法打开文件");
        }
    }
    
    ~FileHandle() {
        if (file) fclose(file);
    }
    
    // 禁用拷贝
    FileHandle(const FileHandle&) = delete;
    FileHandle& operator=(const FileHandle&) = delete;
    
    // 允许移动
    FileHandle(FileHandle&& other) : file(other.file) {
        other.file = nullptr;
    }
};

// 2. 使用标准异常类型
void validateInput(int value) {
    if (value < 0) {
        throw std::invalid_argument("输入值不能为负数");
    }
    if (value > 100) {
        throw std::out_of_range("输入值超出范围");
    }
}

// 3. 提供有意义的错误信息
class DatabaseException : public std::runtime_error {
public:
    DatabaseException(const std::string& msg, int errorCode)
        : std::runtime_error(msg + " (错误码: " + std::to_string(errorCode) + ")") {}
};

🎯 7.总结

C++异常机制是现代C++错误处理的核心工具,它提供了与传统错误码完全不同的错误处理范式:

主要特点:
  1. 分离正常逻辑和错误处理:使代码更清晰、更易维护
  2. 自动资源管理:结合RAII可以避免资源泄漏
  3. 类型安全:异常是类型化的,可以携带丰富的信息
  4. 跨函数传播:异常可以跨多层函数调用传播
使用原则:
  1. 异常用于异常情况:不要用异常处理正常的控制流
  2. 优先使用标准异常:除非有特殊需求,否则使用标准库异常
  3. 保证异常安全:使用RAII等技术确保资源安全
  4. 提供清晰的错误信息:异常消息应该有助于调试
现代C++改进:
  • noexcept说明符:C++11引入,用于标记不会抛出异常的函数
  • 移动语义:配合异常安全,提高性能
  • 智能指针:自动管理内存,减少异常安全问题

在实际项目中,通常建议:

  • 在应用程序层使用异常,提供清晰的错误处理
  • 在底层库或性能关键代码中谨慎使用异常
  • 统一项目的异常使用规范,避免混用异常和错误码

通过合理使用异常机制,可以编写出更健壮、更易维护的C++代码。

更多推荐