1. 程式人生 > 資訊 >OpenHarmony 3.0 將至,開放原子基金會與 Eclipse 合作助開源鴻蒙進軍歐洲

OpenHarmony 3.0 將至,開放原子基金會與 Eclipse 合作助開源鴻蒙進軍歐洲

異常概述


異常:在JAva語言中,將程式執行過程中發生的不正常的情況稱為“異常”。


一、異常體系結構
java.lang.Throwable
|-----java.lang.Error:一般不編寫針對性的程式碼進行處理。
|-----java.lang.Exception:可以進行異常的處理
  |------編譯時異常(checked(受檢異常))
   |-----IOException
   |-----FileNotFoundException
   |-----ClassNotFoundException

|------執行時異常(unchecked(非受檢異常),RuntimeException)
  |-----NullPointerException
   |-----ArrayIndexOutOfBoundsException
   |-----ClassCastException
   |-----NumberFormatException
   |-----InputMismatchException
   |-----ArithmeticException
public class ExceptionTest {
    
    //******************以下是編譯時異常***************************
    @Test
    public void test7(){
//        File file = new File("hello.txt");
//        FileInputStream fis = new FileInputStream(file);
//        
//        int data = fis.read();
//        while(data != -1){
//            System.out.print((char)data);
// data = fis.read(); // } // // fis.close(); } //******************以下是執行時異常*************************** //ArithmeticException @Test public void test6(){ int a = 10; int b = 0; System.out.println(a / b); } //InputMismatchException @Test public void test5(){ Scanner scanner = new Scanner(System.in); int score = scanner.nextInt(); System.out.println(score); scanner.close(); } //NumberFormatException @Test public void test4(){ String str = "123"; str = "abc"; int num = Integer.parseInt(str); } //ClassCastException @Test public void test3(){ Object obj = new Date(); String str = (String)obj; } //IndexOutOfBoundsException @Test public void test2(){ //ArrayIndexOutOfBoundsException // int[] arr = new int[10]; // System.out.println(arr[10]); //StringIndexOutOfBoundsException String str = "abc"; System.out.println(str.charAt(3)); } //NullPointerException @Test public void test1(){ // int[] arr = null; // System.out.println(arr[3]); String str = "abc"; str = null; System.out.println(str.charAt(0)); } }
異常舉例說明
二、Java異常處理的方式
  方式一:try - catch - finally
  方式二、throws + 異常型別

三、異常處理 :抓拋模型
 過程一:"拋":程式在正常執行的過程中,一旦出現異常,就會在異常程式碼處生成一個對應異常類的物件。並將此物件丟擲。
一旦丟擲物件以後,其後的程式碼就不再執行。

關於異常物件的產生:① 系統自動生成的異常物件
   ② 手動的生成一個異常物件,並丟擲(throw

過程二:"抓":可以理解為異常的處理方式:① try-catch-finally ② throws


二、try-catch-finally的使用
 try{
     //可能出現異常的程式碼
 
 }catch(異常型別1 變數名1){
    //處理異常的方式1
 }catch(異常型別2 變數名2){
     //處理異常的方式2
 }catch(異常型別3 變數名3){
     //處理異常的方式3
 }
 ....
 finally{
     //一定會執行的程式碼
 }

說明:
1. finally是可選的。
2. 使用try將可能出現異常程式碼包裝起來,在執行過程中,一旦出現異常,就會生成一個對應異常類的物件,根據此物件的型別,
去catch中進行匹配
3. 一旦try中的異常物件匹配到某一個catch時,就進入catch中進行異常的處理。一旦處理完成,就跳出當前的try-catch結
   構(在沒有寫finally的情況)。繼續執行其後的程式碼
4. catch中的異常型別如果沒有子父類關係,則誰宣告在上,誰宣告在下無所謂。
catch中的異常型別如果滿足子父類關係,則要求子類一定宣告在父類的上面。否則,報錯
5. 常用的異常物件處理的方式: ① getMessage()獲取異常資訊,返回字串
   ② printStackTrace()獲取異常類名和異常資訊,以及異常出現在程式中的位置。返回值void。

6. 在try結構中宣告的變數,再出了try結構以後,就不能再被呼叫
7. try-catch-finally結構可以巢狀

體會1:使用try-catch-finally處理編譯時異常,是得程式在編譯時就不再報錯,但是執行時仍可能報錯。
相當於我們使用try-catch-finally將一個編譯時可能出現的異常,延遲到執行時出現

體會2:開發中,由於執行時異常比較常見,所以我們通常就不針對執行時異常編寫try-catch-finally了。
     針對於編譯時異常,我們說一定要考慮異常的處理。
public class ExceptionTest1 {
    
    
    @Test
    public void test2(){
        try{
            File file = new File("hello.txt");
            FileInputStream fis = new FileInputStream(file);
            
            int data = fis.read();
            while(data != -1){
                System.out.print((char)data);
                data = fis.read();
            }
            
            fis.close();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    
    @Test
    public void test1(){
        
        String str = "123";
        str = "abc";
        int num = 0;
        try{
            num = Integer.parseInt(str);
            
            System.out.println("hello-----1");
        }catch(NumberFormatException e){
//            System.out.println("出現數值轉換異常了,不要著急....");
            //String getMessage():
//            System.out.println(e.getMessage());
            //printStackTrace():
            e.printStackTrace();
        }catch(NullPointerException e){
            System.out.println("出現空指標異常了,不要著急....");
        }catch(Exception e){
            System.out.println("出現異常了,不要著急....");
            
        }
        System.out.println(num);
        
        System.out.println("hello-----2");
    }
    
}
try -- catch例項

try-catch-finally中finally的使用:

1.finally是可選的

2.finally中宣告的是一定會被執行的程式碼。即使catch中又出現異常了,try中有return語句,catch中有
return語句等情況。

3.像資料庫連線、輸入輸出流、網路程式設計Socket等資源,JVM是不能自動的回收的,我們需要自己手動的進行資源的釋放。
  此時的資源釋放,就需要宣告在finally中。



異常處理的方式二:throws + 異常型別
  1. "throws + 異常型別"寫在方法的宣告處。指明此方法執行時,可能會丟擲的異常型別。
一旦當方法體執行時,出現異常,仍會在異常程式碼處生成一個異常類的物件,此物件滿足throws後異常型別時,就會被丟擲。
   異常程式碼後續的程式碼,就不再執行!

2. 體會:try-catch-finally:真正的將異常給處理掉了。 throws的方式只是將異常拋給了方法的呼叫者。並沒有真正將異常處理掉。

3. 開發中如何選擇使用try-catch-finally 還是使用throws?
3.1 如果父類中被重寫的方法沒有throws方式處理異常,則子類重寫的方法也不能使用throws,意味著如果子類重寫
    的方法中有異常,必須使用try-catch-finally方式處理。子類重寫的方法丟擲異常不大於父類被重寫方法的異常型別。

3.2 執行的方法a中,先後又呼叫了另外的幾個方法,這幾個方法是遞進關係執行的。我們建議這幾個方法使用throws
的方式進行處理。而執行的方法a可以考慮使用try-catch-finally方式進行處理。
class Student{
    
    private int id;
    
    public void regist(int id) throws Exception {
        if(id > 0){
            this.id = id;
        }else{
//            System.out.println("您輸入的資料非法!");
            //手動丟擲異常物件
//            throw new RuntimeException("您輸入的資料非法!");
//            throw new Exception("您輸入的資料非法!");
            throw new MyException("不能輸入負數");
            //錯誤的
//            throw new String("不能輸入負數");
        }
        
    }

    @Override
    public String toString() {
        return "Student [id=" + id + "]";
    }
    
    
}
手動丟擲異常物件

四、如何自定義異常類?
   1. 繼承於現有的異常結構:RuntimeException 、Exception
   2. 提供全域性常量:serialVersionUID
   3. 提供過載的構造器
public class MyException extends Exception{
    
    static final long serialVersionUID = -7034897193246939L;
    
    public MyException(){
        
    }
    
    public MyException(String msg){
        super(msg);
    }
}
自定義異常類




throw : 生成一個異常物件,拋
throws : 異常處理的一種方式,抓


面試題:
final、finally、finalize

類似:
throw、throws
String、StringBuffer、StringBuilder
ArrayList、LinkedList
HashMap、LinkedHashMap
重寫、過載

結構不相似:
抽象類、介面
==、equals()
sleep()、wait()