实验目的和要求
1、正确理解C++的异常处理机制。
2、学习异常处理的声明和执行过程。
实验内容
1、下面是一个文件打不开的异常处理程序,分析程序并完成相应问题。
//sy10_1.cpp
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
iftream source("myfile.txt");
char line[128];
try{
if(!source)
throw"myfile.txt";
}
catch(char *s)
{
cout<<"error opening the file"<<s<<endl;
exit(1);
}
while(!source,eof()){
source.getline(line,sizeof(line));
cout<<line<<endl;
}
source.close();
return 0;
}
(1)若磁盘中没有myfile.txt文件,则输出结果如何?
答:则输出结果为error opening the file。
(2)在硬盘上建一个myfile.txt文件,其文件内容自己定义。输出结果如何?
2、声明一个异常类Cexception,有成员函数what(),用来显示异常的类型,在子函数中触发异常ÿ