程式語言與編程實踐7-> Java實操4 | 第三周作業及思路講解 | 異常處理考察

第三周作業,可能是異常那一章當時沒怎麼聽,此前也不怎麼接觸,感覺還挺陌生的。

00 第1題

00-1 題目

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author zzrs123
 */
public class Homework_week3 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int a=0, b=5;
        try{
            System.out.print(a/b+b/a);
        }
        catch
        {
            System.out.println("Exceptions!!!"); 
        }
    }
}

編譯以上程式碼,會出現什麼錯誤?

A. Prints: Exceptions!!! 
B. Prints Nothing 
C. Syntax error 
D. Runtime Error 
E. None of the above 

00-2 解答

Answer: D

catch處語法出錯,導致不能編譯: Uncompilable source code - 非法的類型開始;

如果改為:

catch (ArithmeticException e){
	System.out.println("Exceptions!!!"); 
}

那麼就會輸出Exceptions!!!。

考察的是try + catch + finally異常捕獲機制的語法:如果try{}拋出的對象屬於 catch() 括弧內欲捕獲的異常類,則 catch() 會捕捉此異常,然後進到 catch() 的塊里繼續運行。

01 第2題

01-1 題目

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author zzrs123
 */
public class Homework_week3 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int a=0, b=5;
        String c[] = {"A","B","C"};
        try{
            for(int i = 1;i < 4; i++){
                System.out.print(c[i]);
            }
            System.out.print(a/b+b/a);
        }
        catch (ArithmeticException e)
        {
            System.out.println("D"); 
        }
        catch(ArrayIndexOutOfBoundsException e)
        {
            System.out.println("E");
        }
    }
}

編譯並執行程式碼,會出現哪種結果?

A. Prints: ABC 
B. Prints: ABD 
C. Prints: BCE 
D. Prints: BCDEE. Compiler Error 

01-2 解答

**Answer: **C

這道題就考察了try + catch + finally的運行機制,檢測到for循環里出現數組下標溢出,就拋出異常,產生中斷,接著匹配到第二個catch語句塊catch(ArrayIndexOutOfBoundsException),輸出E。

考察的是try + catch + finally異常捕獲機制的捕獲到異常立刻中斷,進入異常處理。

02 第3題

02-1 題目

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author zzrs123
 */
public class Homework_week3 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int a=0, b=5;
        String c[] = {"A","B","C"};
        try{
            System.out.print(c[a/b]);
            try{
                for(int i = 1;i < 4; i++){
                    System.out.print(c[i]);
                }
            }
            catch (Exception e)
            {
                System.out.println("D"); 
            }
            finally{
                System.out.println("E");
            }
        }
        
        catch(Exception e)
        {
            System.out.println("F");
        }
        finally{
            System.out.println("G");
        }
    }
}

編譯並執行程式碼,會出現哪種結果?

A. Prints: AABCG 
B. Prints: ABCDG 
C. Prints: AABCDG 
D. Prints: AABCDEG 
E. Prints: AABCDEFG

02-2 解答

Answer: D

兩個try + catch + finally的嵌套,考察的知識是:

" 無論 try 程式塊是否有捕捉到異常,或者捕捉到的異常是否與 catch()括弧里的異常相同,最後一定會運行 finally 塊里的程式程式碼。finally 的程式程式碼塊運行結束後,程式再回到 try-catch-finally 塊之後繼續執行。"

03 第4題

03-1 題目

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author zzrs123
 */
public class Homework_week3 {

    /**
     * @param args the command line arguments
     */
    public static void main( String[] args ) {
         int src[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
         int res[] = {1, 2, 3, 4, 5}; 
         System.arraycopy(src, 0, res, 0, src.length);
         for(int i=0; i<res.length; i++) {
             System.out.print(res[i]);
         }
     }
}

What is the result?

A. 10987654321 
B. 10987612345 
C. 12345612345 
D. Compiler error 
E. Runtime exception 

03-2 解答

Answer: E

很明顯,這裡的語句都符合語法,所以Compiler error可以排除;

而arraycopy()函數的語法:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

參數說明:

  • Object src : 原數組
  • int srcPos : 拷貝到原數組的起始位置
  • Object dest : 目標數組
  • int destPos : 目標數組的開始起始位置
  • int length : 要copy的數組的長度

題目中,要向長度為5的數組放入10個元素,所以運行到這個函數的時候,會發生越界錯誤,採取java默認的異常處理機制,直接拋出異常中斷:ArrayIndexOutOfBoundsException。

04 第5題

04-1 題目

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author zzrs123
 */
public class Homework_week3 {

    /**
     * @param args the command line arguments
     */
    public static void main( String[] args ) {
         byte a[] = new byte[2];
         long b[] = new long[2];
         float c[] = new float[2];
         Object d[] = new Object[2];
         System.out.print(a[1]+","+b[1]+","+c[1]+","+d[1]);
     }
}

編譯並執行程式碼,會出現哪種結果?

A. Prints: 0,0,0,null 
B. Prints: 0,0,0.0,null 
C. Prints: 0,0,0,0 
D. Prints: null,null,null,null 
E. The code runs with no output.

04-2 解答

Answer: B

在new一個數組的時候,默認初始化為0,當然,這種初始化契合於數據類型,比如float要初始化為0.0,Object初始化為null。

05 第6題

05-1 題目

1. class A {
2.     public static void main(String[] args) {
3.         int[ ] var1;
4.         int[5] var2;
5.         int[] var3;
6.         int var4[];
7.         }
8.     }

編譯並執行程式碼,會出現哪種結果?

A. compile-time errors occur at line 3 
B. compile-time errors occur at line 4
C. compile-time errors occur at line 5 
D. compile-time errors occur at line 6 
E. None of the above 

05-2 解答

Answer: B

這兩道題考察的都是數組的聲明、分配記憶體和初始化,

一維數組的聲明與分配記憶體:

  1. 數據類型 數組名[ ] ; // 聲明一維數組
  2. 數組名 = new 數據類型[個數] ; // 分配記憶體給數組

聲明數組的同時分配記憶體:

  • 數據類型 數組名[] = new 數據類型[個數]

06 第7題

06-1 題目

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author zzrs123
 */
public class Homework_week3 {

    /**
     * @param args the command line arguments
     */
    static void my() throws ArithmeticException {
         System.out.print("A");
         throw new ArithmeticException("A");
          }
     public static void main (String args []) {
         try { 
             my();
         }
         catch (Exception e) {
             System.out.print("B");
             }
         finally {
             System.out.print("C");
             }
         }
}

編譯並執行程式碼,會出現哪種結果?

A. Prints: A 
B. Prints: AC 
C. Prints: ABC 
D. Prints: AABC 
E. Prints: C 

06-2 解答

Answer: C

考察的是throw指定方法拋出異常的知識:

  1. 用處:

    如果方法內的程式程式碼可能會發生異常,且方法內又沒有使用任何的程式碼塊來捕捉這些異常時,則必須在聲明方法時一併指明所有可能發生的異常,以便讓調用此方法的程式得以做好準備來捕捉異常。也就是說,如果方法會拋出異常,則可將處理這個異常的 try-catch-finally 塊寫在調用此方法的程式程式碼內。

  2. 語法:方法名稱(參數…) throws 異常類 1,異常類 2,…

  3. 具體執行:

    throws 在指定方法中不處理異常,在調用此方法的地方處理,如果指定方法中異常,則在調用處進行處理(進入catch())

所以這道題的運行過程為:main函數-> try()塊-> my函數-> 輸出A -> new ArithmeticException(「A」)-> catch()-> 輸出B-> finally()-> 輸出C

07 第8題

07-1 題目

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author zzrs123
 */
class B extends Exception {}
class C extends B {}
class D extends C {}
public class Homework_week3 {
     /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        int a,b,c,d,x,y,z;
        a = b = c = d = x = y = 0;
        z = 1;
        try {
            try {
                switch(z) {
                   case 1: throw new B();
	           case 2: throw new C();
                   case 3: throw new D();
                   case 4: throw new Exception();
                }
                a++;//a=0
            }
            catch ( C e ) {b++;}//b=0
            finally{c++;}//c=1
        }
        catch ( B e ) {d++;}//d=1
        catch ( Exception e ) {x++;}//x=0
        finally {y++;}//y=1
        System.out.print(a);
        System.out.print(b);
        System.out.print(c);
        System.out.print(d);
        System.out.print(x);
        System.out.print(y);
    }
}

編譯並執行程式碼,會出現哪種結果?

A. 0,0,1,1,0,1 
B. 0,1,0,1,1,0 
C. 0,0,1,1,0,1 
D. 0,1,1,1,1,1 
E. 1,1,0,1,0,0 

07-2 解答

Answer: AC

這道題的亮點是異常類的層層繼承,人腦運行的關鍵在於:如果報了一個類的錯誤,那麼catch其父類和子類的塊會不會響應。

答案是不會,catch只能識別錯誤本身。

此外就是運行到case 1: throw new B();時,程式就中斷,直接進入catch()區,不會運行a++。

08 第9題

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package homework_week3;

/**
 *
 * @author shandaiwang
 */

   
1.class B extends Exception {
2.    public void myMethod( ) throws RuntimeException {}
3.}
4.
5.public class Homework_week3 extends B {
     /**
     * @param args the command line arguments
     */
6.      public void myMethod( ) throws Exception {}
7.      public static void main (String[] args) {}
8.}

編譯錯誤會出現在哪一行?

A. 1 
B. 2 
C. 6 
D. 7 
E. None of the above

08-2 解答

Answer: C

0330 這個問題不是很明白,還是編譯錯誤,所以也很難從IDE得到點什麼,查了查,有兩點:

  1. 子類中覆蓋方法的訪問許可權不能比父類小,比如父類的myMethod( )是public類型,子類的不能是private。
  2. 子類中覆蓋方法拋出的異常只能比父類中原方法拋出的異常低級,比如父類拋出Exception,而子類的覆蓋方法只能拋出RuntimeException之類的子異常。

09 第10題

09-1 題目

class A {
    public static void main (String[] args) {
        int a=1, b=0;
        int c[] = {1,2,3};
        try { 
            System.out.print(c[1]);
            try {
                System.out.print(a/b+b/a);
            }
            catch (ArithmeticException e){
                System.out.print(「C」); 
            } 
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.print(「A」); 
        } 
        finally { 
            System.out.print(「B」);
        }
    }
}

編譯並執行程式碼,會出現哪種結果?

(A) 1BC 
(B) 1CB 
(C) 2BC 
(D) 2CB 
(E) 2AC 

09-2 解答

Answer: D

這道題相對常規,是一個try-catch-finally的嵌套問題,

System.out.print(c[1]);
try {
    System.out.print(a/b+b/a);
}
catch (ArithmeticException e){
    System.out.print(「C」); 
} 

正常輸出c[1] 為2,然後進入內層的 try,發現異常,捕獲輸出 C,接著出來進入外層 try 的catch,未捕獲異常,進入外層的 finally ,輸出 B 。