正文
1. 异常处理
1.1 异常处理基础
在 C++ 中,异常处理机制用于处理程序运行时出现的错误情况。它允许将错误处理代码与正常程序逻辑分离,使程序更加健壮。
异常处理主要使用 try
、catch
和 throw
关键字。try
块中放置可能会抛出异常的代码,catch
块用于捕获并处理异常。
以下是一个简单的示例代码:
#include <iostream>
using namespace std;
int main() {
try {
int num = 5;
if (num > 3) {
throw num;
}
} catch (int e) {
cout << "Caught an exception: " << e << endl;
}
return 0;
}
在这个示例中,当 num > 3
时,通过 throw
抛出一个 int
类型的异常,catch
块会捕获并处理这个异常。
1.2 异常类型和层次结构
C++ 允许自定义异常类型,可以通过继承 std::exception
类或者其子类来创建更具针对性的异常类。
例如,定义一个自定义异常类来表示除以零的情况:
#include <iostream>
#include <exception>
class DivideByZeroException : public std::exception {
public:
const char* what() const noexcept override {
return "Divide by zero exception";
}
};
int main() {
try {
int dividend = 10;
int divisor = 0;
if (divisor == 0) {
throw DivideByZeroException();
}
int result = dividend / divisor;
} catch (const DivideByZeroException& e) {
std::cout << e.what() << std::endl;
} catch (const std::exception& e) {
std::cout << "General exception: " << e.what() << std::endl;
}
return 0;
}
这里创建了 DivideByZeroException
类,它继承自 std::exception
。在 main
函数中,如果除数为零,就会抛出这个自定义异常。catch
块会根据异常类型进行相应的处理。
2. 文件操作
2.1 文件打开和关闭
在 C++ 中,使用 fstream
头文件来进行文件操作。可以创建 ifstream
(用于读取文件)、ofstream
(用于写入文件)和 fstream
(用于读写文件)对象。
以下是打开和关闭文件的示例:
#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "This is a sample text." << std::endl;
outFile.close();
} else {
std::cout << "Unable to open file." << std::endl;
}
return 0;
}
在这个例子中,创建了一个 ofstream
对象来打开名为 example.txt
的文件。如果文件打开成功,就向其中写入一些文本,然后关闭文件。如果打开失败,会输出相应的提示信息。
2.2 文件读取
使用 ifstream
读取文件内容。例如:
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("example.txt");
if (inFile.is_open()) {
std::string line;
while (getline(inFile, line)) {
std::cout << line << std::endl;
}
inFile.close();
} else {
std::cout << "Unable to open file for reading." << std::endl;
}
return 0;
}
这里通过 getline
函数逐行读取文件内容并输出。
2.3 文件读写模式
可以使用不同的模式来打开文件进行读写操作。例如:
#include <iostream>
#include <fstream>
int main() {
std::fstream file("example.txt", std::ios::in | std::ios::out);
if (file.is_open()) {
std::string line;
file.seekg(0, std::ios::end);
int length = file.tellg();
file.seekg(0, std::ios::beg);
char* buffer = new char[length];
file.read(buffer, length);
std::cout << buffer << std::endl;
file.seekp(0, std::ios::beg);
file << "New content added.";
file.close();
delete[] buffer;
} else {
std::cout << "Unable to open file in read - write mode." << std::endl;
}
return 0;
}
在这个示例中,使用 fstream
以读写模式打开文件。先读取文件内容,然后在文件开头添加新的内容。注意对文件指针的操作以及内存的正确管理。
结语
感谢您的阅读!期待您的一键三连!欢迎指正!