首頁 > 軟體

Java開發過程中關於例外處理的詳解

2021-10-23 22:00:47

1.執行java時,出現了異常:

我這裡是因為:arr[3]不存在:
java.lang.ArrayIndexOutOfBoundsException: 3

public class btyf {

    public static void main(String[] args){

      int[] arr={1,2,3};
      System.out.println(arr[0]);
        System.out.println(arr[3]);
System.out.println(arr[1]);


//1 異常
        ArrayIndexOutOfBoundsException  異常名
        // btyf.main(btyf.java:13)      異常位置第13行
        //

//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
//	at btyf.main(btyf.java:13)

    }
}

結果:

java虛擬機器器:會把異常內容輸出控制檯

2.處理異常:

public class btyf {

    
    public static void main(String[] args){

        
      int[] arr={1,2,3};
      System.out.println(arr[0]);

      
try{
    System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e) {
    
    System.out.println("你存取的陣列索引不存在");

e.printStackTrace();  //輸出異常資料:控制檯
}
        System.out.println(arr[1]);

//1 異常
       // ArrayIndexOutOfBoundsException  異常名
        // btyf.main(btyf.java:13)      異常位置

//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
//	at btyf.main(btyf.java:13)

    }


}

結果:
通過try抓異常,後面沒有異常的程式碼就不會因為前面的程式碼一些異常而停止,
就可以執行

3.throwable:成員方法:

System.out.println(e.toString());//列印出異常內容:位置和名稱
e.printStackTrace(); //輸出異常資料:控制檯
System.out.println(e.getMessage()); 一樣
多用:System.out.println(e.toString());這個

try{
    System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e) {

    //System.out.println("你存取的陣列索引不存在");
   // e.printStackTrace();
    System.out.println(e.getMessage());

    
    //public String getMessage() {
    //        return detailMessage;
    //    }
    
    System.out.println(e.toString());
}

結果:

4.throws:丟擲異常:


但是在異常處:還是要新增try catch

新增位置:異常成員方法
public static void main(String[] args)throws ArrayIndexOutOfBoundsException{}

程式碼:

public class uytig {


    public static void main(String[] args)throws ArrayIndexOutOfBoundsException{


        int[] arr={1,2,3};
        System.out.println(arr[0]);


        try {
            System.out.println(arr[3]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("執行中");

}


}

到此這篇關於Java開發過程中關於例外處理的詳解的文章就介紹到這了,更多相關Java 異常內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com