C++ 异常处理:基础使用与自定义异常

引言

在 C++ 编程中,异常处理是一项至关重要的技术,它能够增强程序的健壮性和容错能力。当程序运行过程中出现错误时,异常处理机制可以让程序有序地处理这些错误,避免程序崩溃。本文将详细介绍 C++ 异常处理的基础使用方法,并探讨如何自定义异常类,同时结合具体的使用场景进行说明。

一、C++ 异常处理的基础使用

1.1 基本语法

在 C++ 中,异常处理主要通过 trycatch 和 throw 关键字来实现。try 块用于包含可能抛出异常的代码,throw 用于抛出异常,catch 块用于捕获并处理异常。以下是一个简单的示例代码:

cpp

#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw std::runtime_error("test1");
    } catch (const std::range_error& e) {
        if (e.what() == std::string("test1")) {
            // 处理特定的 std::range_error 异常
        }
        // 处理 std::range_error 异常
    } catch (const std::runtime_error& e) {
        // 可选:处理 std::runtime_error 的其他子类异常
    } catch (const std::exception& e) {
        // 可选:处理所有标准异常的基类 std::exception
    } catch (...) {
        // 处理所有其他异常
    }
    return 0;
}

1.2 代码解释

  • try 块try 块中包含了可能抛出异常的代码。在上述示例中,throw std::runtime_error("test1"); 语句抛出了一个 std::runtime_error 类型的异常。
  • catch 块catch 块用于捕获并处理异常。可以有多个 catch 块,每个 catch 块可以捕获不同类型的异常。异常类型从具体到一般进行排列,首先捕获 std::range_error 异常,然后是 std::runtime_error 异常,接着是 std::exception 基类异常,最后使用 catch (...) 捕获所有其他异常。
  • what() 方法std::exception 类及其子类都提供了 what() 方法,用于返回异常的描述信息。在上述示例中,通过 e.what() 可以获取异常的描述信息。

二、自定义异常处理

2.1 自定义异常类的定义

在某些情况下,标准异常类可能无法满足我们的需求,这时可以自定义异常类。自定义异常类通常继承自 std::exception 类,并实现 what() 方法。以下是一个自定义异常类的示例代码:

cpp

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

class session_exception : public std::exception {
public:
    session_exception(const std::string &error_msg) : std::exception(), error_msg(error_msg) {}
    const char *what() const noexcept override {
        return error_msg.c_str();
    }
    std::string error_msg;
};

2.2 代码解释

  • 继承 std::exception 类:自定义异常类 session_exception 继承自 std::exception 类,这样可以保证自定义异常类具有标准异常类的基本特性。
  • 构造函数:构造函数接受一个 std::string 类型的参数 error_msg,用于存储异常的描述信息。
  • what() 方法:重写了 std::exception 类的 what() 方法,返回异常的描述信息。

2.3 自定义异常类的使用

以下是一个使用自定义异常类的示例代码:

cpp

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

class session_exception : public std::exception {
public:
    session_exception(const std::string &error_msg) : std::exception(), error_msg(error_msg) {}
    const char *what() const noexcept override {
        return error_msg.c_str();
    }
    std::string error_msg;
};

void readConfig() {
    try {
        // 模拟读取配置文件时出现错误
        throw session_exception("Failed to read config file");
    } catch (const session_exception& e) {
        std::cerr << "Caught session_exception: " << e.what() << std::endl;
        // 设置预值
        // ...
    }
    // 继续执行后续代码
    std::cout << "Continuing with other tasks..." << std::endl;
}

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

2.4 代码解释

  • 抛出异常:在 readConfig() 函数中,使用 throw session_exception("Failed to read config file"); 抛出了一个自定义异常。
  • 捕获异常:在 catch 块中,捕获了 session_exception 类型的异常,并输出异常的描述信息。
  • 继续执行后续代码:在 catch 块执行完后,程序会继续执行 readConfig() 函数中后续的代码。

三、使用场景分析

自定义异常处理适合在一些场景中使用,例如读取配置文件。当读取配置文件时,如果出现错误,可以抛出自定义异常,并在 catch 块中设置预值,然后继续执行后续的代码。这样可以保证程序的健壮性,即使出现错误也不会崩溃。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值