c++++ 异常处理允许创建自定义错误处理例程,通过抛出异常并使用 try-catch 块捕捉异常来处理运行时错误。1. 创建一个派生自 exception 类的自定义异常类并覆盖 what() 方法;2. 使用 throw 关键字抛出异常;3. 使用 try-catch 块捕捉异常并指定可以处理的异常类型。
C++ 异常处理:支持自定义错误处理例程
在 C++ 中,异常处理是一种处理运行时错误的强大机制。它允许您创建自定义错误处理例程,以优雅且高效的方式处理错误情况。
异常类
在 C++ 中,异常由 exception 类或其派生类表示。要抛出一个自定义异常,请创建您自己的派生类并覆盖 what() 方法。此方法返回一个描述错误的字符串。
class MyCustomException : public std::exception {
public:
const char* what() const noexcept override {
return "This is my custom exception.";
}
};
抛出异常
使用 throw 关键字抛出异常。它接受一个异常对象作为参数:
throw MyCustomException();
捕捉异常
使用 try-catch 块捕捉异常。每个 catch 子句都指定一个可以处理的异常类型。如果发生匹配类型的异常,将执行该子句中的代码:
try {
// 可能抛出异常的代码
} catch (MyCustomException& e) {
// 处理 MyCustomException 异常
} catch (std::exception& e) {
// 处理所有其他类型的异常
}
实战案例
让我们考虑一个打开文件并对其进行读取的函数。如果无法打开文件,则函数应抛出我们的自定义异常:
#include <fstream>
#include <iostream>
using namespace std;
// 自定义异常类
class FileOpenException : public std::exception {
public:
const char* what() const noexcept override {
return "Could not open the file.";
}
};
// 打开文件并读取其内容的函数
string read_file(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
throw FileOpenException();
}
string contents;
string line;
while (getline(file, line)) {
contents += line + 'n';
}
file.close();
return contents;
}
int main() {
try {
string contents = read_file("file.txt");
cout << contents << endl;
} catch (FileOpenException& e) {
cout << "Error: " << e.what() << endl;
} catch (std::exception& e) {
cout << "An unexpected error occurred." << endl;
}
return 0;
}
在上面的示例中,read_file() 函数抛出 FileOpenException 异常,当文件无法打开时启动。在 main() 函数中,我们使用 try-catch 块来捕捉异常并相应地处理它们。