qfedu-cpp-level/day8/homework/h3.cpp

59 lines
1.4 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个C++ 程序,读取一个文件的内容并打印到控制台。 在文件读取过程中处理以下异常情况: 1如果文件打开失败则抛出一个自定义的异常对象 FileOpenException。 2如果文件读取过程中发生错误则抛出一个自定义的异常对象 FileReadException。
// 【要求】在 main 函数中调用文件读取函数,并捕获并处理可能抛出的异常。
#include <bits/stdc++.h>
using namespace std;
// 自定义异常类
class FileOpenException : public exception
{
public:
const char *what() const throw()
{
return "文件打开异常";
}
};
class FileReadException : public exception
{
public:
const char *what() const throw()
{
return "文件读取异常";
}
};
int main()
{
FILE *fp = fopen("test.txt", "r");
try
{
if (fp == NULL)
{
throw FileOpenException(); // 抛出自定义文件打开异常
}
}
catch (exception &e)
{
cout << "捕获异常: " << e.what() << endl;
}
char ch;
try
{
// EOF 表示到达文件结尾
if (fscanf(fp, "%c", &ch) == EOF)
throw FileReadException(); // 抛出自定义文件读取异常
}
catch (exception &e)
{
cout << "捕获异常: " << e.what() << endl;
}
fclose(fp);
return 0;
}