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

34 lines
1.1 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如果文件打开失败则抛出 std::runtime_error 异常类的一个实例,并传递适当的错误消息。 2如果文件读取过程中发生错误则抛出 std::ios_base::failure 异常类的一个实例,并传递适当的错误消息。
// 【要求】在 main 函数中调用文件读取函数,并捕获并处理可能抛出的异常。
#include <bits/stdc++.h>
using namespace std;
int main()
{
FILE *fp = fopen("test.txt", "r");
try
{
if (fp == NULL)
throw std::runtime_error("文件打开异常");
}
catch (const std::runtime_error &e)
{
cout << "捕获异常:" << e.what() << endl;
}
char ch;
try
{
if (fscanf(fp, "%c", &ch) == EOF)
throw std::ios_base::failure("文件读取异常");
}
catch (const std::ios_base::failure &e)
{
cout << "捕获异常:" << e.what() << endl;
}
fclose(fp);
return 0;
}