引言
在 C++ 编程中,异常处理是一项至关重要的技术,它能够增强程序的健壮性和容错能力。当程序运行过程中出现错误时,异常处理机制可以让程序有序地处理这些错误,避免程序崩溃。本文将详细介绍 C++ 异常处理的基础使用方法,并探讨如何自定义异常类,同时结合具体的使用场景进行说明。
一、C++ 异常处理的基础使用
1.1 基本语法
在 C++ 中,异常处理主要通过 try
、catch
和 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
块中设置预值,然后继续执行后续的代码。这样可以保证程序的健壮性,即使出现错误也不会崩溃。