实验十

实验目的和要求

1、正确理解C++的异常处理机制。

2、学习异常处理的声明和执行过程。


实验内容

1、下面是一个文件打不开的异常处理程序,分析程序并完成相应问题。

#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文件,则输出结果如何?

(2)在硬盘上建一个myfile.txt文件,其文件内容自己定义。输出结果如何?

2、声明一个异常类Cexception,有成员函数what(),用来显示异常的类型,在子函数中触发异常,在主程序中处理异常。(sy10_2.cpp)


3、写一个程序(sy10_3.cpp),将24小时格式的时间转换成12小时格式。下面是一个示范的对话:

Enter time in 24-hour notation :

13:07

That is the same as:

1:07 PM

Do you want to try a new case?(y/n)

Y

Enter time in 24-hour notation :

10:15

That is the same as:

10:15 AM

Do you want to try a new case?(y/n)

Y

 Enter time in 24-hour notation :

10:65

There is no such a time as 10:65

Enter another time :

Enter time in 24-hour notation :

16:05

That is the same as:

16:05 PM

Do you want to try a new case?(y/n)

N

End of program.

定义一个名为 TimeFormatMistake 的异常类。如果用户输入非法时间,比如10:65,或者输入一些垃圾字符,比如6&*65,程序就抛出并捕捉一个 TimeFormatMistake 异常。


分析与讨论

 1、结合实验内容中第1题,分析抛出异常和处理异常的执行过程。

2、结合实验内容中第2题,说明异常处理的机制。

3、结合实验内容中第2题和第3题,说明异常类的作用。

猜你喜欢

转载自blog.csdn.net/wanghuai_666/article/details/80730190