1. 程式人生 > >動手動腦第五波異常處理

動手動腦第五波異常處理

 

注意:

1.可以有多個catch語句塊,每個程式碼塊捕獲一種異常。在某個try塊後有兩個不同的catch 塊捕獲兩個相同型別的異常是語法錯誤。
2.使用catch語句,只能捕獲Exception類及其子類的物件。因此,一個捕獲Exception物件的catch語句塊可以捕獲所有“可捕獲”的異常。
3.將catch(Exception e)放在別的catch塊前面會使這些catch塊都不執行,因此Java不會編譯這個程式。

4.

package 異常處理;
public class CatchWho { 
    public static void main(String[] args) { 
        
try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch"); }
throw new ArithmeticException(); //throw new ArrayIndexOutOfBoundsException(); } catch(ArithmeticException e) { System.out.println("發生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch"); } } }

5.

package 異常處理;
public class CatchWho2 { 
    public static void main(String[] args) { 
        try {
                try { 
                    throw new ArrayIndexOutOfBoundsException(); 
                } 
                catch(ArithmeticException e) { 
                    System.out.println( "ArrayIndexOutOfBoundsException" + "/內層try-catch"); 
                }
            throw new ArithmeticException(); 
        } 
        catch(ArithmeticException e) { 
            System.out.println("發生ArithmeticException"); 
        } 
        catch(ArrayIndexOutOfBoundsException e) { 
            System.out.println( "ArrayIndexOutOfBoundsException" + "/外層try-catch"); 
        } 
    } 
}