实验10

 

 

 

实验目的和要求

 

 

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

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

 

实验内容

 

 

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

 

实验名称:                         实验报告序号:                 第2页

=

1.   #include  

2.   #include <fstream>  

3.   #include <iostream>  

4.   using namespace std;  

5.   int main()  

6.   {  

7.       ifstream source("myfile.txt");  

8.       char line[128];  

9.       try{  

10.         if(!source)  

11.            throw"myfile.txt";  

12.     }  

13.     catch(char *s)  

14.     {  

15.         cout<<"error opening the file"<<s<<endl;  

16.         exit(1);  

17.     }  

18.     while(!source.eof()){  

19.         source.getline(line,sizeof(line));  

20.         cout<<line<<endl;  

21.     }  

22.     source.close();  

23.     return 0;  

24. }  



(1)若磁盘中没有myfile.txt文件,则输出结果如何?

答:则输出结果为error opening the file

(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 异常。

[cpp] view plain copy

1.   <span style="font-size:16px;">#include<iostream>  

2.   #include<cstdio>  

3.   #include<stdlib.h>  

4.   #define err(s,x) {perror(s);exit(x);}  

5.   using namespace std;  

6.   int  main()  

7.   {  

8.       int hour=0,fen=0;  

9.       cout<<"Enter time in 24-hour notation :"<<endl;  

10.     cin>>hour>>fen;  

11.   

12.     if(hour>=24 || hour<0)  

13.       err("hour",1);  

14.     if(fen<0 || fen>=60)  

15.       err("fen",2);  

16.     if(hour>12&&hour<24)  

17.     {  

18.         cout<<"That is the same as:"<<endl<<hour-12<<":"<<fen<<" PM"<<endl;  

19.     }  

20.     else  

21.     {  

22.         cout<<"That is the same as:"<<endl<<hour<<":"<<fen<<" AM"<<endl;  

23.     }  

24.      int ch=1;  

25.   

26. }</span>  




分析与讨论

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

 

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

答:C++的异常处理机制使得异常的引发和处理不必在同一函数中。C++异常处理的目的是在异常发生时,尽可能地减小破坏,周密地完善后,而不影响其他部分程序的运行。这样底层烦人函数可以着重解决具体问题,而不必过多地考虑对异常的处理。上层调用者可以在适当的位置设计对不同类型异常的处理,这在大型程序中是非常必的要。

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值