1. 程式人生 > >Java基礎-throw和throws

Java基礎-throw和throws

雖然瞭解一些有關 Java 的異常處理,但是發現自己對 throw 和 throws 二者還不是很清楚,所以想深入的理解理解。

丟擲異常的三種方式

系統自動丟擲異常、throw 和 throws三種方式。

1、系統自動丟擲異常

public class ThrowTest {
    
    public static void main(String[] args) {
        int a = 0;
        int b = 1;
        System.out.println(b / a);
    }

}

執行該程式後系統會自動丟擲 ArithmeticException 算術異常。

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

2、throw
throw 指的是語句丟擲異常,後面跟的是物件,如:throw new Exception,一般用於主動丟擲某種特定的異常,如:

public class ThrowTest {
    
    public static void main(String[] args) {
        String string = "abc";
        if ("abc".equals(string)) {
            throw new NumberFormatException();
        } else {
            System.out.println(string);
        }
    }

}

執行後丟擲指定的 NumberFormatException 異常。

Exception in thread "main" java.lang.NumberFormatException
    at com.sywf.study.ThrowTest.main(ThrowTest.java:8)

3、throws
throws 用於方法名後,宣告方法可能丟擲的異常,然後交給呼叫其方法的程式處理,如:

public class ThrowTest {

    public static void test() throws ArithmeticException {
        int a = 0;
        int b = 1;
        System.out.println(b / a);
    }

    public static void main(String[] args) {
        try {
            test();
        } catch (ArithmeticException e) {
            // TODO: handle exception
            System.out.println("test() -- 算術異常!");
        }
    }

}

程式執行結果:

test() -- 算術異常!

throw 與 throws 比較

1、throw 出現在方法體內部,而 throws 出現方法名後。
2、throw 表示丟擲了異常,執行 throw 則一定丟擲了某種特定異常,而 throws 表示方法執行可能會丟擲異常,但方法執行並不一定發生異常。