1. 程式人生 > 其它 >18-02 異常的丟擲 & finally關鍵字

18-02 異常的丟擲 & finally關鍵字

技術標籤:Java基礎java

異常的丟擲

thorws 的方式處理異常:

  • 定義功能方法時,需要把出現的問題暴露出來讓呼叫者去處理
  • 那麼就需要通過 throws 在方法上標識

編譯時異常:

public class Demo4_Exception {
    public static void main(String[] args) throws Exception{
        Person p = new Person();
        p.setAge(-17);
        System.out.println(p.getAge());
    }
}

class
Person{ private String name; private int age; public Person() { } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) throws
Exception{ if(age > 0 && age < 200){ this.age = age; } else { throw new Exception("年齡非法"); } } }

用同樣的方式寫執行時異常:

public class Demo4_Exception {
    public static void main(String[] args) {
        Person p = new Person();
        p.
setAge(-17); System.out.println(p.getAge()); } } class Person{ private String name; private int age; public Person() { } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { if(age > 0 && age < 200){ this.age = age; } else { throw new RuntimeException("年齡非法"); } } }

不需要在函式名上寫 throws Exception 了!!

throws 和 throw 的區別

  • throws
    - 用在方法聲明後面,跟的是異常類名
    - 可以跟多個異常類名,用逗號隔開
    - 表示丟擲異常,由該方法的呼叫者來處理
  • throw
    - 只能用在方法體內,跟的是異常物件名
    - 只能丟擲一個異常物件
    - 表示丟擲異常,由方法體內的語句處理

finally關鍵字

特點:

  • 被 finally 控制的語句體一定會執行
  • 特使情況,除非執行到 finally 之前程式退出了(如 System.exit(0))

作用:

  • 用於釋放資源,在IO流操作和資料庫操作中會見到
public class Demo5_Finally {
    public static void main(String[] args) {
        try{
            System.out.println(10 / 2);
        } catch (Exception e){
            e.printStackTrace();
            return ;
        } finally {
            System.out.println("看看我執行了嗎");
        }
    }
}

即便丟擲了異常,即便捕捉異常後面跟了 return 語句,finally 語句也還是會執行。注意,千萬不要在 finally 語句體內寫 return 語句,因為它的作用是釋放資源的。

下面看一下 return 和 finally 的時機:

public class Test1 {
    public static void main(String[] args) {
        Demo demo = new Demo();
        System.out.println(demo.method());
    }
}

class Demo {
    public int method(){
        int x = 10;
        try{
            x = 20;
            System.out.println(1 / 0);
            return x;
        } catch (Exception e){
            x = 30;
            return x;
        } finally {
            x = 40;
        }
    }
}

輸出:
在這裡插入圖片描述
說明:

  • 方法先執行的 return 語句,建立了返回通路
  • 在真正返回之前,看一下有沒有 finally 語句,如果有就執行
  • 雖然在 finally 裡改變了 x 的值,但是返回通路已經建立, 返回的 x 的值是 30 的。