201621123061《Java程序設計》第10次學習總結

1. 本週學習總結

1.1 以你喜歡的方式(思惟導圖或其餘)概括總結異常相關內容。

2. 書面做業

本次PTA做業題集異常javascript

1. 經常使用異常

結合題集題目7-1回答java

1.1 本身之前編寫的代碼中常常出現什麼異常、須要捕獲嗎(爲何)?應如何避免?

  • 數組越界的問題;還有空指針,好比一個數組是空的,卻直接要算數組的長度,這時候就會出現空指針問題;強制轉換會出現ClassCastException;
  • 這些異常通常不須要,由於是在運行的時候出現的異常。
  • 使用try-catch處理異常。數據庫

    1.2 什麼樣的異常要求用戶必定要使用捕獲處理?

    除了error和RuntimeException以外的異常都須要捕獲。編程

2. 處理異常使你的程序更加健壯

題集題目7-2數組

2.1 實驗總結。並回答:怎麼樣才能讓你的程序更加健壯?

try{
                String input=sc.next();
                arr[i]=Integer.parseInt(input);
                i++;
            }catch(Exception e){
                System.out.println(e);
            }

在try程序塊中放可能會出現異常的代碼,當輸入非整數的字符串時,會出現異常,則用catch捕獲。
要處理異常可使程序更加健壯。安全

3. throw與throws

題集題目7-3
閱讀Integer.parsetInt源代碼app

3.1 Integer.parsetInt一開始就有大量的拋出異常的代碼,這種作法有什麼好處?

這樣能夠不用絞盡腦汁去考慮各類錯誤,能夠爲處理某一類錯誤提供有效的解決方法,使編程效率提升。dom

3.2 結合本身編寫的程序與3.1,分析本身編寫的方法拋出異常時通常須要傳遞給調用者一些什麼信息?

public static double findMax(double[] arr,int begin, int end) throws IllegalArgumentException{
        if(begin>=end)
            throw new IllegalArgumentException("begin:"+begin+">="+"end:"+end);
        else if(begin<0)
            throw new IllegalArgumentException("begin:"+begin+"<0");
        else if(end>arr.length)
            throw new IllegalArgumentException("end:"+end+">"+"arr.length");
        double max=arr[begin+1];//findMax方法用來返回arr數組中在下標begin(不包含begin)與end-1之間(包括end-1)的最大值。
        for(int i=begin+1;i<end;i++){
            if(max<arr[i]){
                max=arr[i];
            }
        }
        return max;
    }

當begin>=end,begin<0,end>arr.length時會拋出異常,且在異常中寫明異常的緣由。讓調用者明白爲何產生異常,從而尋找方法。ide

4. 用異常改進ArrayIntegerStack

題集題目6-3函數

4.1 結合6-3代碼,回答使用拋出異常的方式表明程序運行時出錯有什麼好處?比單純的返回錯誤值,有何優勢?

好處:出錯信息能夠更詳細,讓用戶更好發現錯誤。在本題中方法push(),若是棧滿就拋出FullStackException,方法pop()和peek()要判斷棧空,若是棧空就要拋出EmptyStackException,單純返回錯誤值,信息太過簡略,並且頗有可能錯誤代碼也是正確的結果(好比-1),而拋出異常能夠避免這些問題。

4.2 若是一個方法內部的內碼拋出的是RuntimeException類型的異常,那麼方法聲明是否應該使用throws關鍵字,若是使用throws關鍵字聲明該方法拋出的異常,能給咱們帶來什麼好處嗎?

  • 能夠不throws,由於RuntimeException不是必須被捕獲的,不必定要拋出異常。
  • 好處:代碼中含有checked Exception,使用throws關鍵字拋出異常,能夠不用辛辛苦苦地寫try-catch子句。

    5. 函數題-多種異常的捕獲

題集題目6-1

5.1 結合6-1代碼,回答:一個try塊中若是可能拋出多種異常,且異常之間可能有繼承關係,捕獲時須要注意些什麼?

子類異常必定要放在父類異常以前。

5.2 一個try塊中若是可能拋出多種異常,使用Java8的多重異常捕獲語法須要注意些什麼?

try塊中後要跟多個catch塊,catch塊中的異常不得有繼承關係。

6. 爲以下代碼加上異常處理

byte[] content = null;
FileInputStream fis = new FileInputStream("testfis.txt");
int bytesAvailabe = fis.available();//得到該文件可用的字節數
if(bytesAvailabe>0){
    content = new byte[bytesAvailabe];//建立可容納文件大小的數組
    fis.read(content);//將文件內容讀入數組
}
System.out.println(Arrays.toString(content));//打印數組內容

6.1 改正代碼,並增長以下功能。當找不到文件時,需提示用戶找不到文件xxx,請從新輸入文件名,而後嘗試從新打開。 若是是其餘異常則提示打開或讀取文件失敗!

注1:裏面有多個方法都可能拋出異常。
功能2:須要添加finally關閉文件。不管上面的代碼是否產生異常,總要提示關閉文件ing。若是關閉文件失敗,提示關閉文件失敗!

byte[] content = null;
try{
    FileInputStream fis = new FileInputStream("testfis.txt");
    int bytesAvailabe = fis.available();//得到該文件可用的字節數
    if(bytesAvailabe>0){
        content = new byte[bytesAvailabe];//建立可容納文件大小的數組
        fis.read(content);//將文件內容讀入數組
    }
}catch(FileNotFoundException | SizeDetermineFailed | MemoryAllocateFailed | ReadFailed e){
    e.getStackTrace();
}finally{
    if (fis != null) {
        try {                     //關閉資源也有可能出錯
             fis.close();
         } catch (IOException e) {
             e.printStackTrace();
             System.out.println("找不到文件xxx,請從新輸入文件名");
         }catch(Exception e){
            System.out.println("打開或讀取文件失敗!");
        }
     }
}
System.out.println(Arrays.toString(content));//打印數組內容

6.2 結合題集6-2代碼,要將什麼樣操做放在finally塊?爲何?使用finally關閉資源須要注意一些什麼?

將關閉資源的操做放在finally塊,由於finally塊裏的代碼始終都要執行。有時候在關閉資源的時候也會遇到異常,這時候也要捕獲。

6.3 使用Java7中的try-with-resources來改寫上述代碼實現自動關閉資源。簡述這種方法有何好處?

byte[] content = null;
try(FileInputStream fis = new FileInputStream("testfis.txt")){
     int bytesAvailabe = fis.available();//得到該文件可用的字節數
     if(bytesAvailabe>0){
        content = new byte[bytesAvailabe];//建立可容納文件大小的數組
        fis.read(content);//將文件內容讀入數組
     }
}catch(Exception e){
    e.printStackTrace();
}

System.out.println(Arrays.toString(content));

7. 面向對象設計做業-圖書館管理系統(分組完成,每組不超過3個同窗)

登陸lib.jmu.edu.cn,對圖書進行搜索。而後登陸圖書館信息系統,查看個人圖書館。若是讓你實現一個圖書借閱系統,嘗試使用面向對象建模。

7.1 該系統的使用者有誰?

集美大學的教師和學生,以及圖書系統管理員。

7.2 主要功能模塊(不要太多)及每一個模塊的負責人。下週每一個人要提交本身負責的模塊代碼及運行視頻。

暫時打算本身完成,算給本身一個挑戰吧。。。

7.3 該系統的主要的類設計及類圖(可用)

7.4 你準備如何存儲圖書信息、解決信息、讀者信息等。

暫時打算分紅三個主要模塊解決,分別爲用戶登陸,用戶管理模塊,借閱管理模塊,圖書管理模塊,和退出系統。系統須要添加圖書、修改圖書、刪除圖書、添加用戶、修改用戶、刪除用戶、借閱圖書、歸還圖書和查閱圖書等過程。爲了安全和方便,打算用數據庫來存儲這些信息,能夠採用表的形式來描述圖書信息、解決信息、讀者信息。

8. 選作:使用異常改進你的購物車系統

舉1個例子說明你是如何使用異常處理機制讓你的程序變得更健壯。
說明要包含2個部分:1. 問題說明(哪裏會碰到異常)。2.解決方案(關鍵代碼)

1.在登陸的時候,若是輸入未存在的帳號,則會無響應。
2.拋出異常

關鍵代碼:
try{
if (Shopping.this.map.get(userInput.getText()).equals(s)) {
    new Menu().setVisible(true);
    Login.this.dispose();
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, "該帳號不存在,請從新輸入!");
}

3.碼雲及PTA

題目集:異常

3.1. 碼雲代碼提交記錄

在碼雲的項目中,依次選擇「統計-Commits歷史-設置時間段」, 而後搜索並截圖

3.2 截圖PTA題集完成狀況圖

須要有兩張圖(1. 排名圖。2.PTA提交列表圖)

3.3 統計本週完成的代碼量

須要將每週的代碼統計狀況融合到一張表中。

周次 行數 新增行數 文件數 新增文件數
1 91 91 5 5
2 504 413 18 13
3 1092 588 28 10
5 1158 129 34 6
6 1539 381 40 6
7 2023 484 49 9
8 2477 454 57 8
9 2709 232 63 6
10 3156 447 70 7
11 3531 375 79 9

4. 拓展

課外練習

JavaTutorial中Questions and Exercises
練習總結

try {
    
} finally {
    
}
  • Yes

2.What exception types can be caught by the following handler?

catch (Exception e) {
     
}

What is wrong with using this type of exception handler?

  • All exceptions can be captured because all exceptions are inherited Exception.
  • The disadvantage is that you can't do specific processing according to specific exceptions.

3.Is there anything wrong with the following exception handler as written? Will this code compile ?

try {

} catch (Exception e) {
    
} catch (ArithmeticException a) {
    
}
  • Exception is the parent of all exceptions, so in the first catch block, the Exception will be captured.The second catch block will never execute.Compilation cannot pass.

4.Match each situation in the first list with an item in the second list.

int[] A;
A[0] = 0;
The JVM starts running your program, but the JVM can't find the Java platform classes. (The Java platform classes reside in classes.zip or rt.jar.)
A program is reading a stream and reaches the end of stream marker.
Before closing the stream and after reaching the end of stream marker, a program tries to read the stream again.
_b_error
_d_checked exception
_a_compile error
_c_no exception

Exercises

1.Add a readList method to ListOfNumbers.java. This method should read in int values from a file, print each value, and append them to the end of the vector. You should catch all appropriate errors. You will also need a text file containing numbers to read in.

2.Modify the following cat method so that it will compile.

public static void cat(File file) {
    RandomAccessFile input = null;
    String line = null;

    try {
        input = new RandomAccessFile(file, "r");
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
        return;
    } finally {
        if (input != null) {
            input.close();
        }
    }
}

修改以下:

相關文章
相關標籤/搜索