實驗10 異常處理(P295)

實驗目的和要求

1.正確理解C++的異常處理機制。

2.學習異常處理的聲明和執行過程。

實驗內容

1.下面是一個文件打不開的異常處理程序,分析程序並完成相應問題。

//sy10_1.cpp
#include
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
    ifstream 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(),用來顯示異常的類型,在子函數中觸發異常,在主程序中處理異常。(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 異常。

#include<iostream>
#include<cstdio>
#include<stdlib.h>
#define err(s,x) {perror(s);exit(x);}
using namespace std;
int  main()
{
    int hour=0,fen=0;
    cout<<"Enter time in 24-hour notation :"<<endl;
    cin>>hour>>fen;

    if(hour>=24 || hour<0)
      err("hour",1);
    if(fen<0 || fen>=60)
      err("fen",2);
    if(hour>12&&hour<24)
    {
        cout<<"That is the same as:"<<endl<<hour-12<<":"<<fen<<" PM"<<endl;
    }
    else
    {
        cout<<"That is the same as:"<<endl<<hour<<":"<<fen<<" AM"<<endl;
    }
     int ch=1;

}



分析與討論

 1、結合實驗內容中第1題,分析拋出異常和處理異常的執行過程。


2、結合實驗內容中第2題,說明異常處理的機制。

答:C++的異常處理機制使得異常的引發和處理不必在同一函數中。C++異常處理的目的是在異常發生時,儘可能地減小破壞,周密地完善後,而不影響其他部分程序的運行。這樣底層煩人函數可以着重解決具體問題,而不必過多地考慮對異常的處理。上層調用者可以在適當的位置設計對不同類型異常的處理,這在大型程序中是非常必要的。

3、結合實驗內容中第2題和第3題,說明異常類的作用。

實驗總結

  通過本次實驗,我知道了異常處理機制的作用是用於管理程序運行期間出現非正常情況的一種結構化方法。C++的異常處理將異常的檢測與異常處理分離,增加了程序的可讀性。異常處理能夠提高程序的健壯性。理解了有哪些異常類,以及出現異常的解決方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章