實驗目的和要求
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題,說明異常類的作用。